
/*>>>>>>>>>> engine.js <<<<<<<<<<*/
// See: http://www.crockford.com/javascript/jslint.html
/*global alert, window, document, navigator, DOMParser, XMLHttpRequest */

/**
 * Declare a constructor function to which we can add real functions.
 * @constructor
 */

function DWREngine()
{
}

/**
 * Constants to pick the XMLHttpRequest remoting method.
 * For example:
 * <code>DWREngine.setMethod(DWREngine.XMLHttpRequest);</code>
 * @see DWREngine.setMethod()
 * @see DWREngine.IFrame
 */
DWREngine.XMLHttpRequest = 1;


/**
 * Constants to pick the iframe remoting method.
 * For example:
 * <code>DWREngine.setMethod(DWREngine.IFrame);</code>
 * @see DWREngine.setMethod()
 * @see DWREngine.XMLHttpRequest
 */
DWREngine.IFrame = 2;

/**
 * The default error handler displays an alert box, but that is not correct
 * for all applications, so this method allows you to set an alternative
 * error handler.
 * By default there is no error handler set.
 * @param handler A function to call with single an error parameter on failure
 * @see DWREngine.defaultMessageHandler()
 */
DWREngine.setErrorHandler = function(handler)
{
    DWREngine._errorHandler = handler;
};




/**
 * The default warning handler displays an alert box, but that is not correct
 * for all applications, so this method allows you to set an alternative
 * warning handler.
 * By default there is no error handler set.
 * @param handler A function to call with single an warning parameter on failure
 * @see DWREngine.defaultMessageHandler()
 */
DWREngine.setWarningHandler = function(handler)
{
    DWREngine._warningHandler = handler;
};


/**
 * The Pre-Hook is called before any DWR remoting is done.
 * Pre hooks can be useful for displaying "please wait" messages.
 * @param handler A function to call with no params before remoting
 * @see DWREngine.setPostHook()
 */
DWREngine.setPreHook = function(handler)
{
    DWREngine._preHook = handler;
};

/**
 * The Post-Hook is called after any DWR remoting is done.
 * Pre hooks can be useful for removing "please wait" messages.
 * @param handler A function to call with no params after remoting
 * @see DWREngine.setPreHook()
 */
DWREngine.setPostHook = function(handler)
{
    DWREngine._postHook = handler;
};

/**
 * Set the preferred remoting method.
 * setMethod does not guarantee that the selected method will be used, just that
 * we will try that method first.
 * @param newmethod One of DWREngine.XMLHttpRequest or DWREngine.IFrame
 */
DWREngine.setMethod = function(newmethod)
{
    if (newmethod != DWREngine.XMLHttpRequest && newmethod != DWREngine.IFrame)
    {
        if (DWREngine._errorHandler)
        {
            DWREngine._errorHandler("Remoting method must be one of DWREngine.XMLHttpRequest or DWREngine.IFrame");
        }

        return;
    }

    DWREngine._method = newmethod;
};

/**
 * Which HTTP verb do we use so send results?
 * Must be one of "GET" or "POST".
 * @param verb the new HTTP verb.
 */
DWREngine.setVerb = function(verb)
{
    if (verb != "GET" && verb != "POST")
    {
        if (DWREngine._errorHandler)
        {
            DWREngine._errorHandler("Remoting verb must be one of GET or POST");
        }

        return;
    }

    DWREngine._verb = verb;
};

/**
 * Do we attempt to ensure that remote calls happen in the order in which they
 * were sent? (Default: false)
 * Warning: Setting this to true will slow down your application, and could
 * leave users with an unresponsive browser if a message gets lost.
 * Sometimes there are better solutions where you make your application use the
 * asynchronous model properly. Please think before you use this method.
 * @param ordered true or false
 */
DWREngine.setOrdered = function(ordered)
{
    DWREngine._ordered = ordered;
};

/**
 * The default message handler.
 * Useful in calls to setErrorHandler() or setWarningHandler() to allow you to
 * get the default back.
 * @param message The message to display to the user somehow
 */
DWREngine.defaultMessageHandler = function(message)
{
    if (typeof message == "object" && message.name == "Error" && message.description)
    {
        alert("Error: " + message.description);
    }
    else
    {
        alert(message);
    }
};

/**
 * You can group several remote calls together using a batch.
 * This saves on round trips to the server so there is much less latency involved.
 * @see DWREngine.endBatch()
 */
DWREngine.beginBatch = function()
{
    if (DWREngine._batch)
    {
        if (DWREngine._errorHandler)
        {
            DWREngine._errorHandler("Batch already started.");
        }

        return;
    }

    // Setup a batch
    DWREngine._batch = {};
    DWREngine._batch.map = {};
    DWREngine._batch.paramCount = 0;
    DWREngine._batch.map.callCount = 0;
    DWREngine._batch.metadata = {};
};

/**
 * We are finished grouping a set of remote calls together, now go and execute
 * them all.
 */
DWREngine.endBatch = function()
{
    if (DWREngine._batch == null)
    {
        if (DWREngine._errorHandler)
        {
            DWREngine._errorHandler("No batch in progress.");
        }

        return;
    }


    // If we are in ordered mode, then we don't send unless the list of sent
    // items is empty
    if (!DWREngine._ordered)
    {
        DWREngine._sendData(DWREngine._batch);
        DWREngine._batches[DWREngine._batches.length] = DWREngine._batch;
    }
    else
    {
        if (DWREngine._batches.length == 0)
        {
            // We aren't waiting for anything, go now.
            DWREngine._sendData(DWREngine._batch);
            DWREngine._batches[DWREngine._batches.length] = DWREngine._batch;
        }
        else
        {
            // Push the batch onto the waiting queue
            DWREngine._batchQueue[DWREngine._batchQueue.length] = DWREngine._batch;
        }
    }

    DWREngine._batch = null;
};

//==============================================================================
// Only private stuff below here
//==============================================================================


/**
 * A function to call if something fails.
 * @private
 */
DWREngine._errorHandler = DWREngine.defaultMessageHandler;

/**
 * A function to call to alert the user to some breakage.
 * @private
 */
DWREngine._warningHandler = DWREngine.defaultMessageHandler;

/**
 * A function to be called before requests are marshalled. Can be null.
 * @private
 */
DWREngine._preHook = null;

/**
 * A function to be called after replies are received. Can be null.
 * @private
 */
DWREngine._postHook = null;

/**
 * An array of the batches that we have sent and are awaiting a reply on.
 * @private
 */
DWREngine._batches = [];

/**
 * An array of batches that we'd like to send, but because we are in ordered
 * mode we won't until the current batch has been returned.
 * @private
 */
DWREngine._batchQueue = [];

/**
 * A map of all the known current batches
 * @private
 */
DWREngine._callbacks = {};

/**
 * What is the default remoting method
 * @private
 */
DWREngine._method = DWREngine.XMLHttpRequest;

/**
 * What is the default remoting verb (ie GET or POST)
 * @private
 */
DWREngine._verb = "POST";

/**
 * Do we attempt to ensure that remote calls happen in the order in which they
 * were sent?
 * @private
 */
DWREngine._ordered = false;

/**
 * The current batch (if we are in batch mode)
 * @private
 */
DWREngine._batch = null;

/**
 * Called when the replies are received.
 * This method is called by Javascript that is emitted by server
 * @param id The identifier of the call that we are handling a response for
 * @param reply The data to pass to the callback function
 * @private
 */
DWREngine._handleResponse = function(id, reply, httpRequestAllowed, authenticated, sessionValidated)
{
    var func = DWREngine._callbacks[id];

    // Clear this callback out of the list - we don't need it any more
    DWREngine._callbacks[id] = null;

    if (func)
    {
        // Error handlers inside here indicate an error that is nothing to do
        // with DWR so we handle them differently.
        try
        {
			if (!httpRequestAllowed)
			{
				DWREngine._httpRequestMethodDenied("Request Denied");
			}
			else if (!authenticated)
			{
				DWREngine._authenticationFailureHandler("Client Authentication failed");
			}
			else if (!sessionValidated)
			{
				DWREngine._sessionAuthenticationFailureHandler("Session Authentication failed");
			}
			else
			{
	            func(reply);
			}
        }
        catch (ex)
        {
            if (DWREngine._errorHandler)
            {
                DWREngine._errorHandler(ex);
            }
        }
    }
    else
    {
        // If there is no reply then we don;t worry about warning for a missing
        // callback function.
        if (reply)
        {
            if (DWREngine._warningHandler)
            {
                 //DWREngine._warningHandler("Internal Error: Missing callback for id='" + id + "'");
            }
        }
    }
};

/**
 * Called when errors are received.
 * This method is called by Javascript that is emitted by server
 * @private
 */
DWREngine._handleError = function(id, reason)
{
    if (DWREngine._errorHandler)
    {
        DWREngine._errorHandler(reason);
    }
};

/**
 * Call right at the end of a batch being executed to clear up
 * @param batch The batch to tidy up after
 * @private
 */
DWREngine._finalize = function(batch)
{
    DWREngine._removeNode(batch.div);
    DWREngine._removeNode(batch.iframe);
    DWREngine._removeNode(batch.form);

    if (DWREngine._postHook)
    {
        DWREngine._postHook();
    }

    // TODO: There must be a better way???
    for (var i = 0; i < DWREngine._batches.length; i++)
    {
        if (DWREngine._batches[i] == batch)
        {
            DWREngine._batches.splice(i, 1);
            break;
        }
    }

    // If there is anything on the queue waiting to go out, then send it.
    // We don't need to check for ordered mode, here because when ordered mode
    // gets turned off, we still process *waiting* batches in an ordered way.
    if (DWREngine._batchQueue.length != 0)
    {
        var batch = DWREngine._batchQueue.shift();
        DWREngine._sendData(batch);
        DWREngine._batches[DWREngine._batches.length] = batch;
    }
};

/**
 * Remove a node from a document.
 * @param node the node to remove from the document that it's part of.
 * @private
 */
DWREngine._removeNode = function(node)
{
    if (node)
    {
        node.parentNode.removeChild(node);
    }
};

/**
 * Send a request to the server
 * This method is called by Javascript that is emitted by server
 * @param path The part of the URL after the host and before the exec bit
 *             without leading or trailing /s
 * @param scriptName The class to execute
 * @param methodName The method on said class to execute
 * @param func The callback function to which any returned data should be passed
 *             if this is null, any returned data will be ignored
 * @param vararg_params The parameters to pass to the above class
 * @private
 */
DWREngine._execute = function(path, scriptName, methodName, vararg_params)
{
    var singleShot = false;
    if (DWREngine._batch == null)
    {
        DWREngine.beginBatch();
        singleShot = true;
    }

    // To make them easy to manipulate we copy the arguments into an args array
    var args = [];
    for (var i = 0; i < arguments.length - 3; i++)
    {
        args[i] = arguments[i + 3];
    }

    // All the paths MUST be to the same servlet
    if (DWREngine._batch.path == null)
    {
        DWREngine._batch.path = path;
    }
    else
    {
        if (DWREngine._batch.path != path)
        {
            if (DWREngine._errorHandler)
            {
                DWREngine._errorHandler("Can't batch requests to multiple DWR Servlets.");
            }

            return;
        }
    }

    // From the other params, work out which is the function (or object with
    // call meta-data) and which is the call parameters
    var func;
    var params;
    var metadata;

    var firstArg = args[0];
    var lastArg = args[args.length - 1];
    
    if (typeof firstArg == "function")
    {
        func = args.shift();
        params = args;
        metadata = {};
    }
    else if (typeof lastArg == "function")
    {
        func = args.pop();
        params = args;
        metadata = {};
    }
    else if (typeof lastArg == "object" && lastArg.callback != null && typeof lastArg.callback == "function")
    {
        metadata = args.pop();
        params = args;
        func = metadata.callback;
    }
    else if (firstArg == null)
    {
        // This could be a null callback function, but if the last arg is also
        // null then we can't tell which is the function unless there are only
        // 2 args, in which case we don't care!
        if (lastArg == null && args.length > 2)
        {
            if (DWREngine._warningHandler)
            {
                DWREngine._warningHandler("Ambiguous nulls at start and end of parameter list. Which is the callback function?");
            }
        }

        func = args.shift();
        params = args;
        metadata = {};
    }
    else if (lastArg == null)
    {
        func = args.pop();
        params = args;
        metadata = {};
    }
    else
    {
        if (DWREngine._warningHandler)
        {
            DWREngine._warningHandler("Missing callback function or metadata object.");
        }

        return;
    }

    // Get a unique ID for this call
    var random = Math.floor(Math.random() * 10001);
    var id = (random + "_" + new Date().getTime()).toString();
    // var id = DWREngine._batches.length;
    // var id = idbase++;
   
    DWREngine._callbacks[id] = func;

    var prefix = "c" + DWREngine._batch.map.callCount + "-";

    // merge the metadata from this call into the batch
    if (metadata != null)
    {
        for (var prop in metadata)
        {
            DWREngine._batch.metadata[prop] = metadata[prop];
        }
    }

    DWREngine._batch.map[prefix + "scriptName"] = scriptName;
    DWREngine._batch.map[prefix + "methodName"] = methodName;
    DWREngine._batch.map[prefix + "id"] = id;

    // Serialize the parameters into batch.map
    DWREngine._addSerializeFunctions();
    for (i = 0; i < params.length; i++)
    {
        DWREngine._serializeAll(DWREngine._batch, [], params[i], prefix + "param" + i);
    }
    DWREngine._removeSerializeFunctions();

    // Now we have finished remembering the call, we incr the call count
    DWREngine._batch.map.callCount++;

    if (singleShot)
    {
        DWREngine.endBatch();
    }
};

/**
 * Called as a result of a request timeout or an http reply status != 200
 * @param batch Block of data about the calls we are making on the server
 * @private
 */ 
DWREngine._abortRequest = function(batch)
{
    if (batch && batch.metadata && batch.completed != true)
    {
        batch.completed = true;
        if (batch.req != null)
        {
            batch.req.abort();

            if (batch.metadata.errorHandler)
            {
                if (typeof batch.metadata.errorHandler == "string")
                {
                    eval(batch.metadata.errorHandler); 
                }
                else if (typeof batch.metadata.errorHandler == "function")
                {
                    batch.metadata.errorHandler(); 
                }
                else
                {
                    if (DWREngine._warningHandler)
                    {
                        DWREngine._warningHandler("errorHandler is neither a string (for eval()) or a function.");
                    }
                }
            }
        }
    }
};

/**
 * Actually send the block of data in the batch object.
 * @param batch Block of data about the calls we are making on the server
 * @private
 */
DWREngine._sendData = function(batch)
{
    // Actually make the call
    if (DWREngine._preHook)
    {
        DWREngine._preHook();
    }

    // Set a timeout
    if (batch.metadata && batch.metadata.timeout)
    {
        var funcReq = function() { DWREngine._abortRequest(batch); };
        setTimeout(funcReq, batch.metadata.timeout);
	}

    // Get setup for XMLHttpRequest if possible
    if (DWREngine._method == DWREngine.XMLHttpRequest)
    {
        if (window.XMLHttpRequest)
        {
            batch.req = new XMLHttpRequest();
        }
        // IE5 for the mac claims to support window.ActiveXObject, but throws an error when it's used
        else if (window.ActiveXObject && !(navigator.userAgent.indexOf('Mac') >= 0 && navigator.userAgent.indexOf("MSIE") >= 0))
        {
            batch.req = new window.ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    // A quick string to help people that use web log analysers
    var statsInfo;
    if (batch.map.callCount == 1)
    {
        statsInfo = batch.map["c0-scriptName"] + "." + batch.map["c0-methodName"];
    }
    else
    {
        statsInfo = "Multiple." + batch.map.callCount;
    }

	var query = "ajax=true&";
    var prop;

    if (batch.req)
    {
        batch.map.xml = true;
		

        // Proceed using XMLHttpRequest
        batch.req.onreadystatechange = function() { DWREngine._stateChange(batch); };

        // Force Mac people to use GET because Safari is broken.
        if (DWREngine._verb == "GET" || navigator.userAgent.indexOf('Safari') >= 0)
        {
			//add authentication Key
			query += encodeURIComponent("clientAuthenticationKey") + "=" + encodeURIComponent(DWREngine.clientAuthenticationKey) + "&";

			for (prop in batch.map)
            {
                query += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
            }
            query = query.substring(0, query.length - 1);
			
            try
            {
                batch.req.open("GET", batch.path + "?" + query);
                batch.req.send(null);
            }
            catch (ex)
            {
                if (DWREngine._errorHandler)
                {
                    DWREngine._errorHandler(ex);
                }
            }
        }
        else
        {
			//add authentication Key
			query += "clientAuthenticationKey" + "=" + encodeURIComponent(DWREngine.clientAuthenticationKey) + "&";
            for (prop in batch.map)
            {
                query += prop + "=" + batch.map[prop] + "&";
            }

            try
            {
				batch.req.open("POST", batch.path + "?" + statsInfo, true);
				batch.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");			
                batch.req.send(query);
            }
            catch (ex)
            {
                if (DWREngine._errorHandler)
                {
                    DWREngine._errorHandler(ex);
                }
            }
        }
    }
    else
    {
        batch.map.xml = false;

        var idname = "dwr-if-" + batch.map["c0-id"];

        // Proceed using iframe
        batch.div = document.createElement('div');
        batch.div.innerHTML = "<iframe id='" + idname + "' name='" + idname + "'></iframe>";
        document.body.appendChild(batch.div);
        batch.iframe = document.getElementById(idname);
        batch.iframe.setAttribute('style', 'width:0px; height:0px; border:0px;');

        if (DWREngine._verb == "GET")
        {
            for (prop in batch.map)
            {
                query += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
            }
            query = query.substring(0, query.length - 1);

            batch.iframe.setAttribute('src', batch.path + "?" + query);
            document.body.appendChild(batch.iframe);
        }
        else
        {
            batch.form = document.createElement('form');
            batch.form.setAttribute('id', 'dwr-form');
            batch.form.setAttribute('action', batch.path);
            batch.form.setAttribute('target', idname);
            batch.form.target = idname;
            batch.form.setAttribute('method', 'post');
            for (prop in batch.map)
            {
                var formInput = document.createElement('input');
                formInput.setAttribute('type', 'hidden');
                formInput.setAttribute('name', prop);
                formInput.setAttribute('value', batch.map[prop]);
                batch.form.appendChild(formInput);
            }

            document.body.appendChild(batch.form);
            batch.form.submit();
        }
    }
};

/**
 * Called by XMLHttpRequest to indicate that something has happened
 * @private
 */
DWREngine._stateChange = function(batch)
{
    if (batch.req.readyState == 4)
    {
        try
        {
            if (batch.req.status && batch.req.status == 200)
            {
                batch.completed = true;
				
				var response = batch.req.responseText;
				if (response.indexOf("****/") > 0)  response = "/****" + response;
				var footerPos = response.indexOf("/* EOF CFAJAX */");
				if (footerPos > 0) response = response.substring(0, footerPos);
                eval(response);
            }
            else
            {
				///////////////////////////document.frm.error.value = batch.req.responseText;
                if (batch.metadata != null)
                {
                    DWREngine._abortRequest(batch);
                }
                else if (DWREngine._errorHandler)
                {
					var response = batch.req.responseText;
					if (response.indexOf("****/") > 0)  response = "/****" + response;
                    DWREngine._errorHandler(response);
                }
            }
        }
        catch (ex)
        {
            if (batch.metadata != null)
            {
                DWREngine._abortRequest(batch);
            }
            else if (DWREngine._errorHandler)
            {
                DWREngine._errorHandler(ex);
            }
        }

        DWREngine._finalize(batch);
    }
};

/**
 * Hack a polymorphic dwrSerialize() function on all basic types. Yeulch
 * @see DWREngine._addSerializeFunctions
 * @private
 */
DWREngine._addSerializeFunctions = function()
{
    Object.prototype.dwrSerialize = DWREngine._serializeObject;
    Array.prototype.dwrSerialize = DWREngine._serializeArray;
    Boolean.prototype.dwrSerialize = DWREngine._serializeBoolean;
    Number.prototype.dwrSerialize = DWREngine._serializeNumber;
    String.prototype.dwrSerialize = DWREngine._serializeString;
    Date.prototype.dwrSerialize = DWREngine._serializeDate;
};

/**
 * Remove the hacked polymorphic dwrSerialize() function on all basic types.
 * @see DWREngine._removeSerializeFunctions
 * @private
 */
DWREngine._removeSerializeFunctions = function()
{
    delete Object.prototype.dwrSerialize;
    delete Array.prototype.dwrSerialize;
    delete Boolean.prototype.dwrSerialize;
    delete Number.prototype.dwrSerialize;
    delete String.prototype.dwrSerialize;
    delete Date.prototype.dwrSerialize;
};

/**
 * Marshall a data item
 * @param batch A map of variables to how they have been marshalled
 * @param referto An array of already marshalled variables to prevent recurrsion
 * @param data The data to be marshalled
 * @param name The name of the data being marshalled
 * @private
 */
DWREngine._serializeAll = function(batch, referto, data, name)
{
    if (data == null)
    {
        batch.map[name] = "null:null";
        return;
    }

    switch (typeof data)
    {
    case "boolean":
        batch.map[name] = "boolean:" + data;
        break;

    case "number":
        batch.map[name] = "number:" + data;
        break;

    case "string":
        batch.map[name] = "string:" + encodeURIComponent(data);
        break;

    case "object":
        if (data.dwrSerialize)
        {
            batch.map[name] = data.dwrSerialize(batch, referto, data, name);
        }
        else
        {
            if (DWREngine._warningHandler)
            {
                DWREngine._warningHandler("Object without dwrSerialize: " + typeof data + ", attempting default converter.");
            }
            batch.map[name] = "default:" + data;
        }
        break;

    case "function":
        // We just ignore functions.
        break;

    default:
        if (DWREngine._warningHandler)
        {
            DWREngine._warningHandler("Unexpected type: " + typeof data + ", attempting default converter.");
        }
        batch.map[name] = "default:" + data;
        break;
    }
};

/**
 * This is for the types that can recurse so we need to check that we've not
 * marshalled this object before.
 * We'd like to do:
 *   var lookup = referto[data];
 * However hashmaps in Javascript appear to use the hash values of the *string*
 * versions of the objects used as keys so all objects count as the same thing.
 * So we need to have referto as an array and go through it sequentially
 * checking for equality with data
 * @private
 */
DWREngine._lookup = function(referto, data, name)
{
    var lookup;
    for (var i = 0; i < referto.length; i++)
    {
        if (referto[i].data == data)
        {
            lookup = referto[i];
            break;
        }
    }

    if (lookup)
    {
        return "reference:" + lookup.name;
    }

    referto.push({ data:data, name:name });
    return null;
};

/**
 * Marshall an object
 * @private
 * @see DWREngine._serializeAll()
 */
DWREngine._serializeObject = function(batch, referto, data, name)
{
    var ref = DWREngine._lookup(referto, this, name);
    if (ref)
    {
        return ref;
    }

    // treat objects as an associative arrays
    var reply = "Object:{";
    var element;
    for (element in this)
    {
        if (element != "dwrSerialize")
        {
            batch.paramCount++;
            var childName = "c" + DWREngine._batch.map.callCount + "-e" + batch.paramCount;
            DWREngine._serializeAll(batch, referto, this[element], childName);

            reply += encodeURIComponent(element);
            reply += ":reference:";
            reply += childName;
            reply += ", ";
        }
    }
    reply = reply.substring(0, reply.length - 2);
    reply += "}";

    return reply;
};

/**
 * Marshall an array
 * @private
 * @see DWREngine._serializeAll()
 */
DWREngine._serializeArray = function(batch, referto, data, name)
{
    var ref = DWREngine._lookup(referto, this, name);
    if (ref)
    {
        return ref;
    }

    var reply = "Array:[";
    for (var i = 0; i < this.length; i++)
    {
        if (i != 0)
        {
            reply += ",";
        }

        batch.paramCount++;
        var childName = "c" + DWREngine._batch.map.callCount + "-e" + batch.paramCount;
        DWREngine._serializeAll(batch, referto, this[i], childName);
        reply += "reference:";
        reply += childName;
    }
    reply += "]";

    return reply;
};

/**
 * Marshall a Boolean
 * @private
 * @see DWREngine._serializeAll()
 */
DWREngine._serializeBoolean = function(batch, referto, data, name)
{
    return "Boolean:" + this;
};

/**
 * Marshall a Number
 * @private
 * @see DWREngine._serializeAll()
 */
DWREngine._serializeNumber = function(batch, referto, data, name)
{
    return "Number:" + this;
};

/**
 * Marshall a String
 * @private
 * @see DWREngine._serializeAll()
 */
DWREngine._serializeString = function(batch, referto, data, name)
{
    return "String:" + encodeURIComponent(this);
};

/**
 * Marshall a Date
 * @private
 * @see DWREngine._serializeAll()
 */
DWREngine._serializeDate = function(batch, referto, data, name)
{
    return "Date:[ " +
        this.getUTCFullYear() + ", " +
        this.getUTCMonth() + ", " +
        this.getUTCDate() + ", " +
        this.getUTCHours() + ", " +
        this.getUTCMinutes() + ", " +
        this.getUTCSeconds() + ", " +
        this.getUTCMilliseconds() + "]";
};

/**
 * Convert an XML string into a DOC object.
 * @param xml The xml string
 * @return a DOM version of the xml string 
 * @private
 */
DWREngine._unserializeDocument = function(xml)
{
    var parser = new DOMParser();
    var dom = parser.parseFromString(xml, "text/xml");

    if (!dom.documentElement || dom.documentElement.tagName == "parsererror")
    {
        var message = dom.documentElement.firstChild.data;
        message += "\n" + dom.documentElement.firstChild.nextSibling.firstChild.data;
        throw message;
    }

    return dom;
};

/**
 * Inform the users that the function they just called is deprecated.
 * @deprecated
 * @private
 */
DWREngine._deprecated = function()
{
    if (DWREngine._warningHandler)
    {
        DWREngine._warningHandler("dwrXxx() functions are deprecated. Please convert to DWREngine.xxx()");
    }
};

/**
 * Stores the encrypted Key created by createClientAuthenticationKey() function
*/
DWREngine.clientAuthenticationKey = "";

DWREngine._authenticationFailureHandler = DWREngine.defaultMessageHandler;
DWREngine._sessionAuthenticationFailureHandler = DWREngine.defaultMessageHandler;
DWREngine._httpRequestMethodDenied = DWREngine.defaultMessageHandler;

DWREngine.setClientAuthenticationKey = function(value)
{
	DWREngine.clientAuthenticationKey = value;
};

DWREngine.setAuthenticationFailureHandler = function(handler)
{
    DWREngine._authenticationFailureHandler = handler;
};

DWREngine.setSessionAuthenticationFailureHandler = function(handler)
{
    DWREngine._sessionAuthenticationFailureHandler = handler;
};

DWREngine.setHttpRequestMethodDeniedHandler = function(handler)
{
    DWREngine._httpRequestMethodDenied = handler;
};



/*>>>>>>>>>> util.js <<<<<<<<<<*/
// See: http://www.crockford.com/javascript/jslint.html
/*global DWREngine, Option, alert, document, setTimeout, window */

/**
 * Declare a constructor function to which we can add real functions.
 * @constructor
 */

function DWRUtil() { }

////////////////////////////////////////////////////////////////////////////////
// The following functions are described in util-compat.html 

/**
 * Enables you to react to return being pressed in an input
 * For example:
 * <code>&lt;input type="text" onkeypressed="DWRUtil.onReturn(event, methodName)"/&gt;</code>
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param event The event object for Netscape browsers
 * @param action Method name to execute when return is pressed
 */
DWRUtil.onReturn = function(event, action)
{
    if (!event)
    {
        event = window.event;
    }

    if (event && event.keyCode && event.keyCode == 13)
    {
        action();
    }
};

/**
 * Select a specific range in a text box.
 * This is useful for 'google suggest' type functionallity.
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The id of the text input element or the HTML element itself
 * @param start The beginning index
 * @param end The end index 
 */
DWRUtil.selectRange = function(ele, start, end)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("selectRange() can't find an element with id: " + orig + ".");
        return;
    }

    if (ele.setSelectionRange)
    {
        ele.setSelectionRange(start, end);
    }
    else if (ele.createTextRange)
    {
        var range = ele.createTextRange();
        range.moveStart("character", start);
        range.moveEnd("character", end - ele.value.length);
        range.select();
    }

    ele.focus();
};

////////////////////////////////////////////////////////////////////////////////
// The following functions are described in util-general.html

/**
 * Find the element in the current HTML document with the given id, or if more
 * than one parameter is passed, return an array containing the found elements.
 * Any non-string arguments are left as is in the reply.
 * This function is inspired by the prototype library however it probably works
 * on more browsers than the original.
 * @see http://www.getahead.ltd.uk/dwr/util-general.html
 */
function $()
{
    var elements = new Array();

    for (var i = 0; i < arguments.length; i++)
    {
        var element = arguments[i];
        if (typeof element == 'string')
        {
            if (document.getElementById)
            {
                element = document.getElementById(element);
            }
            else if (document.all)
            {
                element = document.all[element];
            }
        }

        if (arguments.length == 1) 
        {
            return element;
        }

        elements.push(element);
    }

    return elements;
}

/**
 * A better toString than the default for an Object
 * @param data The object to describe
 * @param level 0 = Single line of debug, 1 = Multi-line debug that does not
 *              dig into child objects, 2 = Multi-line debug that digs into the
 *              2nd layer of child objects
 * @param depth How much do we indent this item?
 * @see http://www.getahead.ltd.uk/dwr/util-general.html
 */
DWRUtil.toDescriptiveString = function(data, level, depth)
{
    var reply = "";
    var i = 0;
    var value;

    if (level == null)
    {
        level = 0;
    }

    if (depth == null)
    {
        depth = 0;
    }

    if (data == null)
    {
        return "null";
    }

    if (DWRUtil._isArray(data))
    {
        reply = "[";
        if (level != 0)
        {
            reply += "\n";
        }

        for (i = 0; i < data.length; i++)
        {
            try
            {
                obj = data[i];

                if (obj == null || typeof obj == "function")
                {
                    continue;
                }
                else if (typeof obj == "object")
                {
                    if (level > 0)
                    {
                        value = DWRUtil.toDescriptiveString(obj, level - 1, depth + 1);
                    }
                    else
                    {
                        value = DWRUtil._detailedTypeOf(obj);
                    }
                }
                else
                {
                    value = "" + obj;
                    value = value.replace(/\/n/g, "\\n");
                    value = value.replace(/\/t/g, "\\t");
                }
            }
            catch (ex)
            {
                value = "" + ex;
            }

            if (level == 0 && value.length > 13)
            {
                value = value.substring(0, 10) + "...";
            }

            reply += value;
            reply += ", ";

            if (level != 0)
            {
                reply += "\n";
            }

            if (level == 0 && i > 5)
            {
                reply += "...";
                break;
            }
        }
        reply += "]";

        return reply;
    }

    if (typeof data == "string" || typeof data == "number" || DWRUtil._isDate(data))
    {
        return data.toString();
    }

    if (typeof data == "object")
    {
        var typename = DWRUtil._detailedTypeOf(data);
        if (typename != "Object")
        {
            reply = typename + " ";
        }

        if (level != 0)
        {
            reply += DWRUtil._indent(level, depth);
        }
        reply += "{";
        if (level != 0)
        {
            reply += "\n";
        }

        var isHtml = DWRUtil._isHTMLElement(data);

        for (var prop in data)
        {
            if (isHtml)
            {
                if (prop.toUpperCase() == prop || prop == "title" ||
                    prop == "lang" || prop == "dir" || prop == "className" ||
                    prop == "form" || prop == "name" || prop == "prefix" ||
                    prop == "namespaceURI" || prop == "nodeType" ||
                    prop == "firstChild" || prop == "lastChild" ||
                    prop.match(/^offset/))
                {
                    // HTML nodes have far too much stuff. Chop out the constants
                    continue;
                }
            }

            value = "";

            try
            {
                obj = data[prop];

                if (obj == null || typeof obj == "function")
                {
                    continue;
                }
                else if (typeof obj == "object")
                {
                    if (level > 0)
                    {
                        value = "\n";
                        value += DWRUtil._indent(level, depth + 2);
                        value = DWRUtil.toDescriptiveString(obj, level - 1, depth + 1);
                    }
                    else
                    {
                        value = DWRUtil._detailedTypeOf(obj);
                    }
                }
                else
                {
                    value = "" + obj;
                    value = value.replace(/\/n/g, "\\n");
                    value = value.replace(/\/t/g, "\\t");
                }
            }
            catch (ex)
            {
                value = "" + ex;
            }

            if (level == 0 && value.length > 13)
            {
                value = value.substring(0, 10) + "...";
            }

            if (level != 0)
            {
                reply += DWRUtil._indent(level, depth + 1);
            }
            reply += prop;
            reply += ":";
            reply += value;
            reply += ", ";

            if (level != 0)
            {
                reply += "\n";
            }

            i++;
            if (level == 0 && i > 5)
            {
                reply += "...";
                break;
            }
        }

        reply += DWRUtil._indent(level, depth);
        reply += "}";

        return reply;
    }

    return data.toString();
};

/**
 * Indenting for DWRUtil.toDescriptiveString
 * @private
 */
DWRUtil._indent = function(level, depth)
{
    var reply = "";
    if (level != 0)
    {
        for (var j = 0; j < depth; j++)
        {
            reply += "--";
        }
        reply += " ";
    }
    return reply;
};

/**
 * Setup a GMail style loading message.
 * @see http://www.getahead.ltd.uk/dwr/util-general.html
 */
DWRUtil.useLoadingMessage = function()
{
    var disabledZone = document.createElement('div');
    disabledZone.setAttribute('id', 'disabledZone');
    disabledZone.style.position = "absolute";
    disabledZone.style.zIndex = "1000";
    disabledZone.style.left = "0px";
    disabledZone.style.top = "0px";
    disabledZone.style.width = "100%";
    disabledZone.style.height = "100%";
    document.body.appendChild(disabledZone);

    var messageZone = document.createElement('div');
    messageZone.setAttribute('id', 'messageZone');
    messageZone.style.position = "absolute";
    messageZone.style.top = "0px";
    messageZone.style.right = "0px";
    messageZone.style.background = "red";
    messageZone.style.color = "white";
    messageZone.style.fontFamily = "Arial,Helvetica,sans-serif";
    messageZone.style.padding = "4px";
    disabledZone.appendChild(messageZone);

    var text = document.createTextNode('Loading');
    messageZone.appendChild(text);

    $('disabledZone').style.visibility = 'hidden';

    DWREngine.setPreHook(function() { $('disabledZone').style.visibility = 'visible'; });
    DWREngine.setPostHook(function() { $('disabledZone').style.visibility = 'hidden'; });
};

////////////////////////////////////////////////////////////////////////////////
// The following functions are described in util-simple.html

/**
 * Set the value for the given id to the specified val.
 * This method works for selects (where the option with a matching value and
 * not text is selected), input elements (including textareas) divs and spans.
 * @see http://www.getahead.ltd.uk/dwr/util-simple.html
 * @param ele The id of the element or the HTML element itself
 */
DWRUtil.setValue = function(ele, val)
{
    if (val == null)
    {
        val = "";
    }

    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("setValue() can't find an element with id: " + orig + ".");
        return;
    }

    if (DWRUtil._isHTMLElement(ele, "select"))
    {
        // search through the values
        var found  = false;
        var i;

        for (i = 0; i < ele.options.length; i++)
        {
            if (ele.options[i].value == val)
            {
                ele.options[i].selected = true;
                found = true;
            }
            else
            {
                ele.options[i].selected = false;
            }
        }

        // If that fails then try searching through the visible text
        if (found)
        {
            return;
        }

        for (i = 0; i < ele.options.length; i++)
        {
            if (ele.options[i].text == val)
            {
                ele.options[i].selected = true;
                break;
            }
        }

        return;
    }

    if (DWRUtil._isHTMLElement(ele, "input"))
    {
        switch (ele.type)
        {
        case "checkbox":
        case "check-box":
        case "radio":
            ele.checked = (val == true);
            return;

        default:
            ele.value = val;
            return;
        }
    }

    if (DWRUtil._isHTMLElement(ele, "textarea"))
    {
        ele.value = val;
        return;
    }

    ele.innerHTML = val;
};

/**
 * The counterpart to setValue() - read the current value for a given element.
 * This method works for selects (where the option with a matching value and
 * not text is selected), input elements (including textareas) divs and spans.
 * @see http://www.getahead.ltd.uk/dwr/util-simple.html
 * @param ele The id of the element or the HTML element itself
 */
DWRUtil.getValue = function(ele)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("getValue() can't find an element with id: " + orig + ".");
        return;
    }

    if (DWRUtil._isHTMLElement(ele, "select"))
    {
        // This is a bit of a scam because it assumes single select
        // but I'm not sure how we should treat multi-select.
        var sel = ele.selectedIndex;
        if (sel != -1)
        {
            var reply = ele.options[sel].value;
            if (reply == null || reply == "")
            {
                reply = ele.options[sel].text;
            }

            return reply;
        }
        else
        {
            return "";
        }
    }

    if (DWRUtil._isHTMLElement(ele, "input"))
    {
        switch (ele.type)
        {
        case "checkbox":
        case "check-box":
        case "radio":
            return ele.checked;

        default:
            return ele.value;
        }
    }

    if (DWRUtil._isHTMLElement(ele, "textarea"))
    {
        return ele.value;
    }

    return ele.innerHTML;
};

/**
 * getText() is like getValue() with the except that it only works for selects
 * where it reads the text of an option and not it's value.
 * @see http://www.getahead.ltd.uk/dwr/util-simple.html
 * @param ele The id of the element or the HTML element itself
 */
DWRUtil.getText = function(ele)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("getText() can't find an element with id: " + orig + ".");
        return;
    }

    if (!DWRUtil._isHTMLElement(ele, "select"))
    {
        alert("getText() can only be used with select elements. Attempt to use: " + DWRUtil._detailedTypeOf(ele) + " from  id: " + orig + ".");
        return;
    }

    // This is a bit of a scam because it assumes single select
    // but I'm not sure how we should treat multi-select.
    var sel = ele.selectedIndex;
    if (sel != -1)
    {
        return ele.options[sel].text;
    }
    else
    {
        return "";
    }
};

/**
 * Given a map, call setValue() for all the entries in the map using the key
 * of each entry as an id.
 * @see http://www.getahead.ltd.uk/dwr/util-simple.html
 * @param map The map of values to set to various elements
 */
DWRUtil.setValues = function(map)
{
    for (var property in map)
    {
        var ele = $(property);
        if (ele != null)
        {
            var value = map[property];
            DWRUtil.setValue(property, value);
        }
    }
};

/**
 * Given a map, call getValue() for all the entries in the map using the key
 * of each entry as an id.
 * @see http://www.getahead.ltd.uk/dwr/util-simple.html
 * @param map The map of values to set to various elements
 */
DWRUtil.getValues = function(map)
{
    for (var property in map)
    {
        var ele = $(property);
        if (ele != null)
        {
            map[property] = DWRUtil.getValue(property);
        }
    }
};

////////////////////////////////////////////////////////////////////////////////
// The following functions are described in util-list.html

/**
 * Add options to a list from an array or map.
 * DWRUtil.addOptions has 5 modes:
 * <p><b>Array</b><br/>
 * DWRUtil.addOptions(selectid, array) and a set of options are created with the
 * text and value set to the string version of each array element.
 * </p>
 * <p><b>Array of objects, using option text = option value</b><br/>
 * DWRUtil.addOptions(selectid, data, prop) creates an option for each array
 * element, with the value and text of the option set to the given property of
 * each object in the array.
 * </p>
 * <p><b>Array of objects, with differing option text and value</b><br/>
 * DWRUtil.addOptions(selectid, array, valueprop, textprop) creates an option
 * for each object in the array, with the value of the option set to the given
 * valueprop property of the object, and the option text set to the textprop
 * property.
 * </p>
 * <p><b>Map (object)</b><br/>
 * DWRUtil.addOptions(selectid, map, reverse) creates an option for each
 * property. The property names are used as option values, and the property
 * values are used as option text, which sounds wrong, but is actually normally
 * the right way around. If reverse evaluates to true then the property values
 * are used as option values.
 * <p><b>ol or ul list</b><br/>
 * DWRUtil.addOptions(ulid, array) and a set of li elements are created with the
 * innerHTML set to the string value of the array elements. This mode works
 * with ul and ol lists.
 * </p>
 * @see http://www.getahead.ltd.uk/dwr/util-list.html
 * @param ele The id of the list element or the HTML element itself
 * @param data An array or map of data items to populate the list
 * @param valuerev (optional) If data is an array of objects, an optional
 *        property name to use for option values. If the data is a map then this
 *        boolean property allows you to swap keys and values.
 * @param textprop (optional) Only for use with arrays of objects - an optional
 *        property name for use as the text of an option.
 */
DWRUtil.addOptions = function(ele, data, valuerev, textprop)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("addOptions() can't find an element with id: " + orig + ".");
        return;
    }

    var useOptions = DWRUtil._isHTMLElement(ele, "select");
    var useLi = DWRUtil._isHTMLElement(ele, ["ul", "ol"]);

    if (!useOptions && !useLi)
    {
        alert("fillList() can only be used with select elements. Attempt to use: " + DWRUtil._detailedTypeOf(ele));
        return;
    }

    // Bail if we have no data
    if (data == null)
    {
        return;
    }

    var text;
    var value;

    if (DWRUtil._isArray(data))
    {
        // Loop through the data that we do have
        for (var i = 0; i < data.length; i++)
        {
            if (useOptions)
            {
                if (valuerev != null)
                {
                    if (textprop != null)
                    {
                        text = data[i][textprop];
                        value = data[i][valuerev];
                    }
                    else
                    {
                        value = data[i][valuerev];
                        text = value;
                    }
                }
                else
                {
                    if (textprop != null)
                    {
                        text = data[i][textprop];
                        value = text;
                    }
                    else
                    {
                        text = "" + data[i];
                        value = text;
                    }
                }

                var opt = new Option(text, value);
                ele.options[ele.options.length] = opt;
            }
            else
            {
                li = document.createElement("li");
                li.innerHTML = "" + data[i];
                ele.appendChild(li);
            }
        }
    }
    else
    {
        for (var prop in data)
        {
            if (!useOptions)
            {
                alert("DWRUtil.addOptions can only create select lists from objects.");
                return;
            }

            if (valuerev)
            {
                text = prop;
                value = data[prop];
            }
            else
            {
                text = data[prop];
                value = prop;
            }

            var opt = new Option(text, value);
            ele.options[ele.options.length] = opt;
        }
    }
};

/**
 * Remove all the options from a select list (specified by id)
 * @see http://www.getahead.ltd.uk/dwr/util-list.html
 * @param ele The id of the list element or the HTML element itself
 */
DWRUtil.removeAllOptions = function(ele)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("removeAllOptions() can't find an element with id: " + orig + ".");
        return;
    }

    var useOptions = DWRUtil._isHTMLElement(ele, "select");
    var useLi = DWRUtil._isHTMLElement(ele, ["ul", "ol"]);

    if (!useOptions && !useLi)
    {
        alert("removeAllOptions() can only be used with select, ol and ul elements. Attempt to use: " + DWRUtil._detailedTypeOf(ele));
        return;
    }

    if (useOptions)
    {
        // Empty the list
        ele.options.length = 0;
    }
    else
    {
        while (ele.childNodes.length > 0)
        {
            ele.removeChild(ele.firstChild);
        }
    }
};

////////////////////////////////////////////////////////////////////////////////
// The following functions are described in util-table.html

/**
 * Create rows inside a the table, tbody, thead or tfoot element (given by id).
 * The normal case would be to use tbody since that allows you to keep header
 * lines separate, but this function should work with and table element above
 * tr.
 * This function creates a row for each element in the <code>data</code> array
 * and for that row create one cell for each function in the
 * <code>cellFuncs</code> array by passing the element from the
 * <code>data</code> array to the given function.
 * The return from the function is used to populate the cell.
 * <p>The pseudo code looks something like this:
 * <pre>
 *   for each member of the data array
 *     for function in the cellFuncs array
 *       create cell from cellFunc(data[i])
 * </pre>
 * One slight modification to this is that any members of the cellFuncs array
 * that are strings instead of functions, the strings are used as cell contents
 * directly.
 * @see http://www.getahead.ltd.uk/dwr/util-table.html
 * @param ele The id of the tbody element
 * @param data Array containing one entry for each row in the updated table
 * @param cellFuncs An array of functions (one per column) for extracting cell
 *    data from the passed row data
 */
DWRUtil.addRows = function(ele, data, cellFuncs)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("addRows() can't find an element with id: " + orig + ".");
        return;
    }

    if (!DWRUtil._isHTMLElement(ele, ["table", "tbody", "thead", "tfoot"]))
    {
        alert("addRows() can only be used with table, tbody, thead and tfoot elements. Attempt to use: " + DWRUtil._detailedTypeOf(ele));
        return;
    }

    // assure bug-free redraw in Gecko engine by
    // letting window show cleared table
    if (navigator.product && navigator.product == "Gecko")
    {
        setTimeout(function() { DWRUtil._addRowsInner(ele, data, cellFuncs); }, 0);
    }
    else
    {
        DWRUtil._addRowsInner(ele, data, cellFuncs);
    }
};

/**
 * Internal function to help rendering tables.
 * @see DWRUtil.addRows(ele, data, cellFuncs)
 * @private
 */
DWRUtil._addRowsInner = function(ele, data, cellFuncs)
{
    var frag = document.createDocumentFragment();

    if (DWRUtil._isArray(data))
    {
        // loop through data source
        for (var i = 0; i < data.length; i++)
        {
            DWRUtil._addRowInner(frag, data[i], cellFuncs);
        }
    }
    else if (typeof data == "object")
    {
        for (var row in data)
        {
            DWRUtil._addRowInner(frag, row, cellFuncs);
        }
    }

    ele.appendChild(frag);
};

/**
 * Iternal function to draw a single row of a table.
 * @private
 */
DWRUtil._addRowInner = function(frag, row, cellFuncs)
{
    var tr = document.createElement("tr");

    for (var j = 0; j < cellFuncs.length; j++)
    {
        var func = cellFuncs[j];
        var td;

        if (typeof func == "string")
        {
            td = document.createElement("td");
            var text = document.createTextNode(func);
            td.appendChild(text);
            tr.appendChild(td);
        }
        else
        {
            var reply = func(row);

            if (DWRUtil._isHTMLElement(reply, "td"))
            {
                td = reply;
            }
            else if (DWRUtil._isHTMLElement(reply))
            {
                td = document.createElement("td");
                td.appendChild(reply);
            }
            else
            {
                td = document.createElement("td");
                td.innerHTML = reply;
                //var text = document.createTextNode(reply);
                //td.appendChild(text);
            }

            tr.appendChild(td);
        }
    }

    frag.appendChild(tr);
};

/**
 * Remove all the children of a given node.
 * Most useful for dynamic tables where you clearChildNodes() on the tbody
 * element.
 * @see http://www.getahead.ltd.uk/dwr/util-table.html
 * @param ele The id of the element or the HTML element itself
 */
DWRUtil.removeAllRows = function(ele)
{
    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("removeAllRows() can't find an element with id: " + orig + ".");
        return;
    }

    if (!DWRUtil._isHTMLElement(ele, ["table", "tbody", "thead", "tfoot"]))
    {
        alert("removeAllRows() can only be used with table, tbody, thead and tfoot elements. Attempt to use: " + DWRUtil._detailedTypeOf(ele));
        return;
    }

    while (ele.childNodes.length > 0)
    {
        ele.removeChild(ele.firstChild);
    }
};

////////////////////////////////////////////////////////////////////////////////
// Private functions only below here

/**
 * Browser detection code.
 * This is eeevil, but the official way [if (window.someFunc) ...] does not
 * work when browsers differ in rendering ability rather than the use of someFunc()
 * For internal use only.
 * @private
 */
DWRUtil._agent = navigator.userAgent.toLowerCase();

/**
 * @private
 */
DWRUtil._isIE = ((DWRUtil._agent.indexOf("msie") != -1) && (DWRUtil._agent.indexOf("opera") == -1));

/**
 * Is the given node an HTML element (optionally of a given type)?
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The element to test
 * @param nodeName eg "input", "textarea" - optional extra check for node name
 *                 or an array of valid node names.
 * @private
 */
DWRUtil._isHTMLElement = function(ele, nodeName)
{
    if (ele == null || typeof ele != "object" || ele.nodeName == null)
    {
        return false;
    }

    if (nodeName != null)
    {
        var test = ele.nodeName.toLowerCase();

        if (typeof nodeName == "string")
        {
            return test == nodeName.toLowerCase();
        }

        if (DWRUtil._isArray(nodeName))
        {
            var match = false;
            for (var i = 0; i < nodeName.length && !match; i++)
            {
                if (test == nodeName[i].toLowerCase())
                {
                    match =  true;
                }
            }

            return match;
        }

        alert("DWRUtil._isHTMLElement was passed test node name that is neither a string or array of strings");
    }
};

/**
 * Like typeOf except that more information for an object is returned other
 * than "object"
 * @private
 */
DWRUtil._detailedTypeOf = function(x)
{
    var reply = typeof x;

    if (reply == "object")
    {
        reply = Object.prototype.toString.apply(x);  // Returns "[object class]"
        reply = reply.substring(8, reply.length-1);  // Just get the class bit
    }

    return reply;
};

/**
 * Array detector.
 * This is an attempt to work around the lack of support for instanceof in
 * some browsers.
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param data The object to test
 * @returns true iff <code>data</code> is an Array
 * @private
 */
DWRUtil._isArray = function(data)
{
    return (data && data.join) ? true : false;
};

/**
 * Date detector.
 * This is an attempt to work around the lack of support for instanceof in
 * some browsers.
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param data The object to test
 * @returns true iff <code>data</code> is a Date
 * @private
 */
DWRUtil._isDate = function(data)
{
    return (data && data.toUTCString) ? true : false;
};

////////////////////////////////////////////////////////////////////////////////
// Deprecated functions only below here

/**
 * Is the given node an HTML element (optionally of a given type)?
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The element to test
 * @param nodeName eg input, textarea - optional extra check for node name
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.isHTMLElement)
{
DWRUtil.isHTMLElement = function(ele, nodeName)
{
    DWRUtil._deprecated("DWRUtil.isHTMLElement");

    if (nodeName == null)
    {
        // If I.E. worked properly we could use:
        //  return typeof ele == "object" && ele instanceof HTMLElement;
        return ele != null &&
               typeof ele == "object" &&
               ele.nodeName != null;
    }
    else
    {
        return ele != null &&
               typeof ele == "object" &&
               ele.nodeName != null &&
               ele.nodeName.toLowerCase() == nodeName.toLowerCase();
    }
};
}

/**
 * Like typeOf except that more information for an object is returned other
 * than "object"
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.detailedTypeOf)
{
DWRUtil.detailedTypeOf = function(x)
{
    DWRUtil._deprecated("DWRUtil.detailedTypeOf");

    var reply = typeof x;

    if (reply == "object")
    {
        reply = Object.prototype.toString.apply(x);  // Returns "[object class]"
        reply = reply.substring(8, reply.length-1);  // Just get the class bit
    }

    return reply;
};
}

/**
 * Array detector.
 * This is an attempt to work around the lack of support for instanceof in
 * some browsers.
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param data The object to test
 * @returns true iff <code>data</code> is an Array
 * @deprecated Not sure if DWR is the right place for this or if we support old browsers
 */
if (!DWRUtil.isArray)
{
DWRUtil.isArray = function(data)
{
    DWRUtil._deprecated("DWRUtil.isArray", "(array.join != null)");
    return (data && data.join) ? true : false;
};
}

/**
 * Date detector.
 * This is an attempt to work around the lack of support for instanceof in
 * some browsers.
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param data The object to test
 * @returns true iff <code>data</code> is a Date
 * @deprecated Not sure if DWR is the right place for this or if we support old browsers
 */
if (!DWRUtil.isDate)
{
DWRUtil.isDate = function(data)
{
    return (data && data.toUTCString) ? true : false;
};
}

/**
 * Is the given node an HTML input element?
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The element to test
 * @deprecated See the documentation for alternatives
 */
if (!DWRUtil.isHTMLInputElement)
{
DWRUtil.isHTMLInputElement = function(ele)
{
    DWRUtil._deprecated("DWRUtil.isHTMLInputElement");
    return DWRUtil.isHTMLElement(ele, "input");
};
}

/**
 * Is the given node an HTML textarea element?
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The element to test
 * @deprecated See the documentation for alternatives
 */
if (!DWRUtil.isHTMLTextAreaElement)
{
DWRUtil.isHTMLTextAreaElement = function(ele)
{
    DWRUtil._deprecated("DWRUtil.isHTMLTextAreaElement");
    return DWRUtil.isHTMLElement(ele, "textarea");
};
}

/**
 * Is the given node an HTML select element?
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The element to test
 * @deprecated See the documentation for alternatives
 */
if (!DWRUtil.isHTMLSelectElement)
{
DWRUtil.isHTMLSelectElement = function(ele)
{
    DWRUtil._deprecated("DWRUtil.isHTMLSelectElement");
    return DWRUtil.isHTMLElement(ele, "select");
};
}

/**
 * Like document.getElementById() that works in more browsers.
 * @param id The id of the element
 * @deprecated Use $()
 */
if (!DWRUtil.getElementById)
{
DWRUtil.getElementById = function(id)
{
    DWRUtil._deprecated("DWRUtil.getElementById", "$");

    if (document.getElementById)
    {
        return document.getElementById(id);
    }
    else if (document.all)
    {
        return document.all[id];
    }

    return null;
};
}

/**
 * Visually enable or diable an element.
 * @see http://www.getahead.ltd.uk/dwr/util-compat.html
 * @param ele The id of the element or the HTML element itself
 * @param state Boolean true/false to set if the element should be enabled
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.setEnabled)
{
DWRUtil.setEnabled = function(ele, state)
{
    DWRUtil._deprecated("DWRUtil.setEnabled");

    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("setEnabled() can't find an element with id: " + orig + ".");
        return;
    }

    // If we want to get funky and disable divs and spans by changing the font
    // colour or something then we might want to check the element type before
    // we make assumptions, but in the mean time ...
    // if (DWRUtil.isHTMLElement(ele, "input")) { ... }

    ele.disabled = !state;
    ele.readonly = !state;
    if (DWRUtil._isIE)
    {
        if (state)
        {
            ele.style.backgroundColor = "White";
        }
        else
        {
            // This is WRONG but the hack will do for now.
            ele.style.backgroundColor = "Scrollbar";
        }
    }
};
}

/**
 * Set the CSS display style to 'block'
 * @param ele The id of the element or the HTML element itself
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.showById)
{
DWRUtil.showById = function(ele)
{
    DWRUtil._deprecated("DWRUtil.showById");

    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("showById() can't find an element with id: " + orig + ".");
        return;
    }

    // Apparently this works better that display = 'block'; ???
    ele.style.display = '';
};
}

/**
 * Set the CSS display style to 'none'
 * @param ele The id of the element or the HTML element itself
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.hideById)
{
DWRUtil.hideById = function(ele)
{
    DWRUtil._deprecated("DWRUtil.hideById");

    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("hideById() can't find an element with id: " + orig + ".");
        return;
    }

    ele.style.display = 'none';
};
}

/**
 * Toggle an elements visibility
 * @param ele The id of the element or the HTML element itself
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.toggleDisplay)
{
DWRUtil.toggleDisplay = function(ele)
{
    DWRUtil._deprecated("DWRUtil.toggleDisplay");

    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("toggleDisplay() can't find an element with id: " + orig + ".");
        return;
    }

    if (ele.style.display == 'none')
    {
        // Apparently this works better that display = 'block'; ???
        ele.style.display = '';
    }
    else
    {
        ele.style.display = 'none';
    }
};
}

/**
 * Alter an rows in a table that have a class of zebra to have classes of either
 * oddrow or evenrow alternately.
 * This is probably not the best place for this method, but I dont want to have
 * to fight with multiple onload functions.
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.alternateRowColors)
{
DWRUtil.alternateRowColors = function()
{
    DWRUtil._deprecated("DWRUtil.alternateRowColors");

    var tables = document.getElementsByTagName("table");
    var rowCount = 0;

    for (var i = 0; i < tables.length; i++)
    {
        var table = tables.item(i);
        var rows = table.getElementsByTagName("tr");

        for (var j = 0; j < rows.length; j++)
        {
            var row = rows.item(j);
            if (row.className == "zebra")
            {
                if (rowCount % 2)
                {
                    row.className = 'oddrow';
                }
                else
                {
                    row.className = 'evenrow';
                }

                rowCount++;
            }
        }

        rowCount = 0;
    }
};
}

/**
 * Set the CSS class for an element
 * @param ele The id of the element or the HTML element itself
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.setCSSClass)
{
DWRUtil.setCSSClass = function(ele, cssclass)
{
    DWRUtil._deprecated("DWRUtil.setCSSClass");

    var orig = ele;
    ele = $(ele);
    if (ele == null)
    {
        alert("setCSSClass() can't find an element with id: " + orig + ".");
        return;
    }

    ele.className = cssclass;
};
}

/**
 * Ensure a function is called when the page is loaded
 * @param load The function to call when the page has been loaded
 * @deprecated DWR isn't a generic Javascript library
 */
if (!DWRUtil.callOnLoad)
{
DWRUtil.callOnLoad = function(load)
{
    DWRUtil._deprecated("DWRUtil.callOnLoad", "window.addEventListener or window.onload");

    if (window.addEventListener)
    {
        window.addEventListener("load", load, false);
    }
    else if (window.attachEvent)
    {
        window.attachEvent("onload", load);
    }
    else
    {
        window.onload = load;
    }
};
}

/**
 * Remove all the options from a select list (specified by id) and replace with
 * elements in an array of objects.
 * @deprecated Use DWRUtil.removeAllOptions(ele); DWRUtil.addOptions(ele, data, valueprop, textprop);
 */
if (!DWRUtil.fillList)
{
DWRUtil.fillList = function(ele, data, valueprop, textprop)
{
    DWRUtil._deprecated("DWRUtil.fillList", "DWRUtil.addOptions");
    DWRUtil.removeAllOptions(ele);
    DWRUtil.addOptions(ele, data, valueprop, textprop);
};
}

/**
 * Add rows to a table
 * @deprecated Use DWRUtil.addRows()
 */
if (!DWRUtil.drawTable)
{
DWRUtil.drawTable = function(ele, data, cellFuncs)
{
    DWRUtil._deprecated("DWRUtil.drawTable", "DWRUtil.addRows");
    DWRUtil.addRows(ele, data, cellFuncs);
};
}

/**
 * Remove all the children of a given node.
 * Most useful for dynamic tables where you clearChildNodes() on the tbody
 * element.
 * @param id The id of the element
 * @deprecated Use DWRUtil.removeAllRows()
 */
if (!DWRUtil.clearChildNodes)
{
DWRUtil.clearChildNodes = function(id)
{
    DWRUtil._deprecated("DWRUtil.clearChildNodes", "DWRUtil.removeAllRows");

    var ele = DWRUtil.getElementById(id);
    if (ele == null)
    {
        alert("clearChildNodes() can't find an element with id: " + id + ".");
        throw id;
    }

    while (ele.childNodes.length > 0)
    {
        ele.removeChild(ele.firstChild);
    }
};
}

/**
 * Do we alert on deprecation warnings
 * @private
 */
DWRUtil._showDeprecated = false;

/**
 * We can use this function to deprecate things.
 * @deprecated
 * @private
 */
DWRUtil._deprecated = function(fname, altfunc)
{
    if (DWRUtil._showDeprecated)
    {
        var warning;
        var alternative; 

        if (fname == null)
        {
            warning = "You have used a deprecated function which could be removed in the future.";
            alternative = "";
        }
        else
        {
            warning = "Utility functions like '" + fname + "' are deprecated and could be removed in the future.";

            if (altfunc == null)
            {
                alternative = "\nSee the documentation for alternatives.";
            }
            else
            {
                alternative = "\nFor an alternative see: " + altfunc;
            }
        }

        var further = "\nImport deprecated.js to get rid of this warning.\nDo you wish to ignore further deprecation warnings on this page?";

        DWRUtil._showDeprecated = !confirm(warning + alternative + further);
    }
};


/*>>>>>>>>>> settings.js <<<<<<<<<<*/
// if the last character in siteURL is not a slash, append one
if (siteUrl.charAt(siteUrl.length-1) != "/")
{
	siteUrl = siteUrl + "/";
}
 
_cfGenericFunctionsLocation = "/cfajax/core/generic.cfm";
_cfBannersFunctionsLocation = "/cfajax/core/marketing/banner.cfm";
_cfShoppingCartFunctionsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/servlet/shoppingCart/addTocartAjax.cfm";
_cfShoppingCartProxyFunctionsLocation = siteUrl + "com/b2c/shoppingCart-proxy.cfc";
_cfEmailFriendFunctionsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/style/sendProductToFriendAjax.cfm";
_cfFabricEmailsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/style/sendFabricEmailsAjax.cfm";
_cfEmailRequestQuoteFunctionsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/style/sendRequestQuoteAjax.cfm";
_cfEmailContactUsFunctionsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/style/sendContactUsEmailAjax.cfm";
_cfNewsLetterLocation = siteUrl + "frontEndComponents/specificComponents/b2c/newsletter/newslettersignUpAjax.cfm";
_cfUserProfileFunctionsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/myaccount/userProfile/userProfileAjax.cfm";
_cfEmailPriceQuoteFunctionsLocation = siteUrl + "frontEndComponents/specificComponents/b2c/style/productDetailsGetQuoteAjax.cfm";

_cfLeftNav = siteUrl + "cfLib/leftNavigationAjax.cfm";
_cfCatLevelsLocation = siteUrl + "cfLib/ajaxCalls.cfm";
_cfCheckOut = siteUrl + "cfLib/checkOutajaxCalls.cfm";
_cfAdminFunctions = "/cfajax/core/adminAjax.cfm";
_cfFactoryFunctions = "/cfajax/core/factoryAjax.cfm";
_cfInTheMediaFunctions = "/cfajax/core/mediaFunctions.cfm";
_cfFreeItemFunctions = "/cfajax/core/freeItemFunctions.cfm";
_pdaFunctions = siteUrl + 'cfLib/global.cfm';
_cfcalendarLocation = siteUrl + 'calendar.cfm';
_cfParametersFunctions = siteUrl+"/cfajax/core/parameterAjax.cfm";
_cfPaymentsFunctions = siteUrl + "cfLib/paymentsAjaxCalls.cfm";
_cfShoppingCartFunctions = siteUrl + "cfLib/shoppingCartAjaxCalls.cfm";
_cfFindItFastFunctions = siteUrl + "cfLib/findItFastAjaxCalls.cfm";
_cfInstoreFunctions = siteUrl + "cfLib/inStoreAjaxCalls.cfm";
_cfAdminSalesFunctions = "/cfLib/adminSalesAjaxCalls.cfm";
_cfGiftcardFunctions = siteUrl + "admin/content/specificComponents/salesSubComponents/GiftCardAjaxCalls.cfm";
_cfAdminEmailFunctions = siteUrl + "cfLib/adminEmailAjaxCalls.cfm";
_cfNavigation = "/cfLib/navigationAjaxCalls.cfm";

_cfVTS6_AjaxCalls = siteUrl + "cfLib/genericAjaxCalls.cfm";
_cfFormGenerator = siteUrl + "cfLib/administration/ajax_formGenerator.cfm";
_cfEmails = siteUrl + "admin/administration/ajax_emails.cfm";
_cfUserRights = siteUrl + "cfLib/administration/ajax_userRights.cfm";
_cfRunwayAjax = siteUrl + "cfLib/runwayAjaxFunctions.cfm";

_cfBannerModuleV2 =  "/cfajax/core/bannersV7_ajax.cfm";
_cfBannerModuleV8 = "/sharedPages/com/b2c/banners/banners_ajax.cfm?ahs=true";
_cfQuickView = siteUrl + "frontEndComponents/specificComponents/b2c/style/showQuickView.cfm";

_cfRefreshSessionFunctionsLocation =  "/frontEndComponents/specificComponents/refreshSessionAjax.cfm";

_cfAdminFunctions_ic_banners="/cfajax/core/adminAjax_ic_banners.cfm";
_cfBannerModule_ic_banners= siteUrl + "cfajax/core/ic_banners_ajax.cfm";

_cfSearchProductsFunctionsLocation = siteUrl + "cfLib/ajaxProductSearch.cfm";

function errorHandler(message)
{
	//$('disabledZone').style.visibility = 'hidden';
    if (typeof message == "object" && message.name == "Error" && message.description)
    {
        alert("Error: " + message.description);
    }
    else
    {
        alert(message);
    }
};


/*>>>>>>>>>> IEbannerFix.js <<<<<<<<<<*/

/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},executeAfterLoad:function(f){
	//Fix by Pedro ... call a function after flash is loaded.
	eval(f);	
},
getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;},getSWFHTML:function(){var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
if (n)
{
n.innerHTML=this.getSWFHTML();return true;
}
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}
catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){
return false;
}return true;};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){if(window.opera||!document.all){return;}
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){_2d[i].style.display="none";for(var x in _2d[i]){
if(typeof _2d[i][x]=="function"){_2d[i][x]=function(){};}}}};
deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=="function"){
var _30=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();_30();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}};
if(typeof window.onbeforeunload=="function"){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
deconcept.SWFObjectUtil.prepUnload();
oldBeforeUnload();};
}else{window.onbeforeunload=deconcept.SWFObjectUtil.prepUnload;}
if(Array.prototype.push==null){
Array.prototype.push=function(_31){
this[this.length]=_31;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;
var SWFObject=deconcept.SWFObject;

/*>>>>>>>>>> global_scripts.js <<<<<<<<<<*/

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function P7_ShowPic(a,b) { //v2.0 by PVII
 var g,gg,d,dd,ic,im;if((g=MM_findObj(b))!=null){
 if(!document.P7ShowPic){document.P7ShowPic=true;}else{
 if((d=MM_findObj(document.P7SPlay))!=null){
  dd=(document.layers)?d:d.style;dd.visibility="hidden";}}
 document.P7SPlay=b;gg=(document.layers)?g:g.style;im=b+"im";
 if((ic=MM_findObj(im))!=null){ic.src=a;gg.visibility="visible";}}
}

function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

document.getElementsByClassName = function(className) {
  var children = document.getElementsByTagName('*') || document.all;
  var elements = new Array();
  
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var classNames = child.className.split(' ');
    for (var j = 0; j < classNames.length; j++) {
      if (classNames[j] == className) {
        elements.push(child);
        break;
      }
    }
  }
  
  return elements;
}

addEvent(document, "click", document_onclick, true);
var iframeIds = ["popUpHoldersizeGuru","popUpHolder"];
function document_onclick(){
	try {
		var divs = document.getElementById("popUpContent");
		if (divs != null) { divs.parentNode.style.display = "none";	}
	} catch (e) {}

	for (var index = 0; index < iframeIds.length; index++){
		var iframe = document.getElementById(iframeIds[index]);
		if (iframe){ iframe.style.display = "none"; }
	}
}
	
function retrieveCartInfo(){
	
		errorFound = checkErrorPage();
		
		 if(!errorFound)
		 { 
		 	if(!document.getElementById('SmartMessage'))
		 	{
		 		new ShoppingCart().get({position:'fixed',posX:570,posY:35,messageTimeout:15000,scrollTop:true,onError:'center', lang: '#variables.actualLang#', parameters:false, onSuccess : _ShoppingCart_action_productDetails_OnSuccess});	
		 	
		 	}
		 }
		 else
		 {
		 	new ShoppingCart().get({position:'fixed',posX:570,posY:35,messageTimeout:15000,scrollTop:true,onError:'center', lang: '#variables.actualLang#', parameters:false, onSuccess : _ShoppingCart_action_productDetails_OnSuccess});	
		 }
}
function _ShoppingCart_action_productDetails_OnSuccess(request){
	_ShoppingCart_action_OnSuccess(request);
}
function checkErrorPage()
{
	ret_er = false;
	if(document.getElementById('SmartMessage'))
	{
		findError = document.getElementById('SmartMessageContent').innerHTML;
		if(findError.toLowerCase().indexOf("<error>") != -1){
  			ret_er = true;
	  	}
	  	else{
	  		ret_er = false;
		}
		/*for(str=findError.length-7;str<=findError.length;str++)
		{
		  	getToken += findError.charAt(str);
		}
		  
		  if(getToken=='<error>'||getToken=='<ERROR>')
		  {
		  	ret_er = true;
		  }
		  else
		  {
		  	ret_er = false;
		  }*/
	}
	return ret_er;
}


function serialize_form(ele,returnArray)
{
	ele = $(ele);
	
	
	/*for(i=0;i<ele.length;i++)
	{
		alert(ele[i].name)
	}*/
	
	//n = (ele.children)?ele.children.length:ele.childNodes.length;
	n = ele.length;
	str_return = "";
	ar_error = new Array();
	
	for(x=0;x<n;x++)
	{
		if(ele[x])
		{
			if(ele[x].tagName != 'FIELDSET' )
			{
			setFormObject(ele[x]);
			val = formObj.value;
			
			
			
			if(ele[x].type.toUpperCase() == 'CHECKBOX'&&!ele[x].checked)
			{
				val = "N";
			}
			if((formObj.toValidate&&validateForm)||formObj._type=='TN'||formObj._type=='EM1')
			{
				formValidation();
			}
			if(formObj.isNumeric)
			{
				str_return+=formObj.name+"|"+val+"~";
			}
			else
			{
				str_return+=formObj.name+"|'"+val+"'~";
			}
			}
		}
	}
	
	if(!returnArray)
		str_return = (ar_error.length>0)?false:str_return;
	else
		str_return = (ar_error.length>0)?ar_error:str_return;
	
	return str_return;
	
}

function formValidation()
{
	if(formObj._type=='TF')
	{
		if(formObj.value.length == 0)
		{
			ar_error.push(formObj.origin); 
		}
		
	}
	
	if(formObj._type=='TN') ///Numeric fields
	{
		if(formObj.value.length == 0||!IsNumber(formObj.value))
		{
			ar_error.push(formObj.origin); 
		}
	}
	
	if(formObj._type=='EM')
	{
		if(formObj.value.length == 0||!testEmail(formObj.value))
		{
			ar_error.push(formObj.origin); 
		}
	}
	
	//for non mandatory email fields
	if(formObj._type=='EM1')
	{
		if(!testEmail(formObj.value) && formObj.value != '')
		{
			ar_error.push(formObj.origin); 
		}
	}
	
	if(formObj._type=='SB')
	{
		if(formObj.value == 0 || formObj.value == '00000' || formObj.value.length == 0)
		{
			ar_error.push(formObj.origin); 
		}
	}
	
	
	if(formObj._type=='CB')
	{
		if(!formObj.checked)
		{
			ar_error.push(formObj.origin); 
		}
	}
}

function setFormObject(i)
{
	fn = i.name.split("_");
	formObj = {name:fn[0],toValidate:(fn[1]=='Y')?true:false,_type:fn[2],isNumeric:(fn[3]=='Y')?true:false,value:i.value,origin:i.name};
}

function FieldsNormalState(e)
{
	e = $(e);
	
	for(z=0;z < e.length;z++)	
	{
		if(e[z])
		{
			if(e[z].tagName.toUpperCase() != 'BUTTON')
			{
				findLabel(e[z],false)
				e[z].className = (e[z].tagName.toUpperCase()=='INPUT')?'inp_' + e[z].type:'inp_' + e[z].tagName;	
			}	
		}	
	}
}

function handle_erros()
{
	for(c=0;c<ar_error.length;c++)
	{
		e = $(ar_error[c]);
		par = (e.parentElement)?e.parentElement:e.parentNode;	
		
		findLabel(e,true)
			
		classError = (e.tagName.toUpperCase()=='INPUT')?'inp_' + e.type:'inp_' + e.tagName;
		e.className = classError+'_error';	
	}
}

function findLabel(obj,error)
{
	
	prev = obj.previousSibling.previousSibling;	

	
	if(prev.htmlFor == obj.id)
	{
		prev.className = (error)?'fieldLabel_error':'fieldLabel';	
	}								
}


function testEmail(src) {
     var emailReg = "^[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$";
     	              
     var regex = new RegExp(emailReg);
     return regex.test(src);
  }
		
function flushForm(e)
{
	for(z=0;z<e.length;z++)	
	{
		if(e[z].type.toUpperCase() != "HIDDEN")
		{
			if(e[z].type.toUpperCase() == "CHECKBOX")
			{
				e[z].checked = false;	
			}
			else if(e[z].tagName.toUpperCase() == "SELECT")
			{
				e[z].selectedIndex = 0;	
			}
			else
			{
				e[z].value = '';	
			}
		}
	}
	FieldsNormalState(e);
}



	function showhide(elem1,elem2,state1,state2)
	
	{ 
	
	document.getElementById(elem1).style.display=state1; 
	
	document.getElementById(elem2).style.display=state2; 
	
	} 
	
	
function showhideChk()
	
	{ 
	 if (document.getElementById('chkDiff').checked)
	 {
	   document.getElementById('chkDiff').value = 'N';
	   document.getElementById('differentAddress').style.display='block';
	 }
	 else
	 {
	   document.getElementById('chkDiff').value = 'Y';
	   document.getElementById('differentAddress').style.display='none';
	   }
	
	 
	}
	

//this function mounts dynamic select box START //
	  function createResultStructure(sel,text,value)
	{
	  
		_ret = {};
		_ret.name = sel;
		_ret.text = text;
		_ret.value = value;
		return _ret;
	}
	
	function updateSelect(result)
	{	
		
		if($(_selObj.name)&&result!='')
		{
			mySelect = $(_selObj.name);
			mySelectChildren = $(_selObj.name).getElementsByTagName('OPTION');
			for(x=mySelectChildren.length-1;x>0;x--)
			{
				$(_selObj.name).removeChild(mySelectChildren[x]);
			}
			
			for(x=0;x<result.length;x++)
			{   
				opt = document.createElement('OPTION');
				opt.innerHTML = result[x][_selObj.text];
				opt.value = result[x][_selObj.value].replace(/^\s+|\s+$/g,"");
				$(_selObj.name).appendChild(opt);
			}
		}
		else
		{
		    mySelect = $(_selObj.name);
			mySelectChildren = $(_selObj.name).getElementsByTagName('OPTION');
			for(x=mySelectChildren.length-1;x>0;x--)
			{
				$(_selObj.name).removeChild(mySelectChildren[x]);
			}
		}
		
	}		
//this function mounts dynamic select box END //		

	
	

	
	function OnclickButton(formId)
	{
		//alert(formId);
		$(formId).submit();
		
	}
	
	
    function checkHasCoordinates(whatFunc)
	{
	  //alert(whatFunc)		
	  funcVar =whatFunc;	
	  DWREngine._execute(_cfShoppingCartFunctions, null, 'checkCoordinatesSession',Hascoordinates_Result);
	}
	
	
	function Hascoordinates_Result(result)
	{
		//alert(result);
		if(result=='TRUE')
		{
			openCoordinatesBag();
			if (funcVar=='shopBag')
			{
			setTimeout('shoppingBagClick()',100000);
			}
			else
			{
			setTimeout('nextFunction()',100000);
			}
		}
		else
		{
			
			if (funcVar=='shopBag')
			{
				shoppingBagClick();
			}
			else
			{
				nextFunction();	
			}
			
		}
	}		
	
	

	sfHover = function() {
	
		if(document.getElementById("topMenuSections"))
		{
			var sfEls = document.getElementById("topMenuSections").getElementsByTagName("LI");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=" sfhover";
					}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
					}
				}
		}
	}
	
	if (window.attachEvent) window.attachEvent("onload", sfHover);

/*>>>>>>>>>> ufo.js <<<<<<<<<<*/
/*	Unobtrusive Flash Objects (UFO) v3.01 <http://www.bobbyvandersluis.com/ufo/>
	Copyright 2005, 2006 Bobby van der Sluis
	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
	------------------------------
	v3.01 Fixed bug: updated domLoad function
*/

var UFO = {
	requiredAttrParams: ["movie", "width", "height", "majorversion", "build"],
	optionalAttrEmb: ["name", "swliveconnect", "align"],
	optionalAttrObj: ["id", "align"],
	optionalAttrParams: ["play", "loop", "menu", "quality", "scale", "salign", "wmode", "bgcolor", "base", "flashvars", "devicefont", "allowscriptaccess"],
	ximovie: "ufo.swf",
	xiwidth: "215",
	xiheight: "138",
	
	is_w3cdom: (typeof document.getElementById != "undefined" && typeof document.getElementsByTagName != "undefined" && (typeof document.createElement != "undefined" || typeof document.createElementNS != "undefined")),
	is_ie: (navigator.userAgent.toLowerCase().indexOf("msie") != -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1),
	is_safari: (navigator.userAgent.toLowerCase().indexOf("safari") != -1),
	is_win: (navigator.userAgent.toLowerCase().indexOf("win") != -1),
	is_mac: (navigator.userAgent.toLowerCase().indexOf("mac") != -1),
	is_XML: (typeof document.contentType != "undefined" && document.contentType.indexOf("xml") > -1),
	
	foList: [],
		
	create: function(FO, id) {
		if (!UFO.is_w3cdom) return;
		UFO.foList[id] = UFO.updateFO(FO);
		UFO.createStyleRule("#" + id, "visibility:hidden;");
		UFO.domLoad(id);
	},

	updateFO: function(FO) {
		if (typeof FO.xi != "undefined" && FO.xi == "true") {
			if (typeof FO.ximovie == "undefined") FO.ximovie = UFO.ximovie;
			if (typeof FO.xiwidth == "undefined") FO.xiwidth = UFO.xiwidth;
			if (typeof FO.xiheight == "undefined") FO.xiheight = UFO.xiheight;
		}
		else {
			FO.xi = false;
		}
		FO.domLoaded = false;
		return FO;
	},

	domLoad: function(id) {
		var timer = setInterval(function() { // doesn't work in IE/Mac
			if((document.getElementsByTagName("body")[0] != null || document.body != null) &&  document.getElementById(id) != null) {
				UFO.main(id);
				clearInterval(timer);
			}
		}, 250);
		if (typeof document.addEventListener != "undefined") {
			document.addEventListener("DOMContentLoaded", function() { UFO.main(id); clearInterval(timer); } , null); // Mozilla only
		}
	},

	main: function(id) {
		var FO = UFO.foList[id];
		if (FO.domLoaded) return; // for Mozilla, only execute once
		UFO.foList[id].domLoaded = true;
		document.getElementById(id).style.visibility = "hidden";
		if (UFO.hasRequiredAttrParams(id)) {
			if (UFO.hasFlashVersion(FO.majorversion, FO.build)) {
				UFO.writeFlashObject(id);
			}
			else if (FO.xi && UFO.hasFlashVersion("6", "65")) {
				UFO.createModalDialog(id);
			}
		}
		document.getElementById(id).style.visibility = "visible";
	},
	
	createStyleRule: function(selector, declaration) {
		if (UFO.is_ie && UFO.is_mac) return; // bugs in IE/Mac
		var head = document.getElementsByTagName("head")[0]; 
		var style = UFO.createElement("style");
		if (!(UFO.is_ie && UFO.is_win)) {
			var styleRule = document.createTextNode(selector + " {" + declaration + "}");
			style.appendChild(styleRule); // bugs in IE/Win
		}
		style.setAttribute("type", "text/css");
		style.setAttribute("media", "screen"); 
		head.appendChild(style);
		if (UFO.is_safari && UFO.is_XML) { head.innerHTML += ""; } // force Safari repaint for MIME type application/xhtml+xml
		if (UFO.is_ie && UFO.is_win && document.styleSheets && document.styleSheets.length > 0) {
			var lastStyle = document.styleSheets[document.styleSheets.length - 1];
			if (typeof lastStyle.addRule == "object") {
				lastStyle.addRule(selector, declaration);
			}
		}
	},

	createElement: function(el) {
		return (typeof document.createElementNS != "undefined") ?  document.createElementNS("http://www.w3.org/1999/xhtml", el) : document.createElement(el);
	},

	hasRequiredAttrParams: function(id) {
		var FO = UFO.foList[id];
		for (var i = 0; i < UFO.requiredAttrParams.length; i++) {
			if (typeof FO[UFO.requiredAttrParams[i]] == "undefined") return false;
		}
		return true;
	},
	
	hasFlashVersion: function(majorVersion, buildVersion) {
		var reqVersion = parseFloat(majorVersion + "." + buildVersion);
		if (navigator.plugins && typeof navigator.plugins["Shockwave Flash"] == "object") {
			var desc = navigator.plugins["Shockwave Flash"].description;
			if (desc) {
				var versionStr = desc.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				var major = parseInt(versionStr.replace(/^(.*)\..*$/, "$1"));
				var build = parseInt(versionStr.replace(/^.*r(.*)$/, "$1"));
				var flashVersion = parseFloat(major + "." + build);
			}
		}
		else if (window.ActiveXObject) {
			try {
				var flashObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				var desc = flashObj.GetVariable("$version");
				if (desc) {
					var versionArr = desc.replace(/^\S+\s+(.*)$/, "$1").split(",");
					var major = parseInt(versionArr[0]);
					var build = parseInt(versionArr[2]);
					var flashVersion = parseFloat(major + "." + build);
				}
			}
			catch(e) {}
		}
		if (typeof flashVersion != "undefined"){
			return (flashVersion >= reqVersion ? true : false); 
		}
		return false;
	},

	writeFlashObject: function(id) {
		var el = document.getElementById(id);
		if (typeof el.innerHTML == "undefined") return;
		var FO = UFO.foList[id];
		if (navigator.plugins && typeof navigator.plugins["Shockwave Flash"] == "object") {
			try	{ // older versions of Gecko only support innerHTML get and not set
				el.innerHTML = "ufo-test";
			}
			catch (e) {}
			if (el.innerHTML != "ufo-test") {
				while(el.hasChildNodes()) {
					el.removeChild(el.firstChild);
				}
				var embed = UFO.createElement("embed");
				embed.setAttribute("type", "application/x-shockwave-flash");
				embed.setAttribute("pluginspage", "http://www.macromedia.com/go/getflashplayer");
				embed.setAttribute("src", FO.movie);
				embed.setAttribute("width", FO.width);
				embed.setAttribute("height", FO.height);
				for (var i = 0; i < UFO.optionalAttrEmb.length; i++) {
					if (typeof FO[UFO.optionalAttrEmb[i]] != "undefined") {
						embed.setAttribute(UFO.optionalAttrEmb[i], FO[UFO.optionalAttrEmb[i]]);
					}
				}
				for (var i = 0; i < UFO.optionalAttrParams.length; i++) {
					if (typeof FO[UFO.optionalAttrParams[i]] != "undefined") {
						embed.setAttribute(UFO.optionalAttrParams[i], FO[UFO.optionalAttrParams[i]]);
					}
				}	
				el.appendChild(embed);
			}
			else {
				var embHTML = "";
				for (var i = 0; i < UFO.optionalAttrEmb.length; i++) {
					if (typeof FO[UFO.optionalAttrEmb[i]] != "undefined") {
						embHTML += ' ' + UFO.optionalAttrEmb[i] + '="' + FO[UFO.optionalAttrEmb[i]] + '"';
					}
				}
				for (var i = 0; i < UFO.optionalAttrParams.length; i++) {
					if (typeof FO[UFO.optionalAttrParams[i]] != "undefined") {
						embHTML += ' ' + UFO.optionalAttrParams[i] + '="' + FO[UFO.optionalAttrParams[i]] + '"';
					}
				}
				el.innerHTML = '<embed type="application/x-shockwave-flash" src="' + FO.movie + '" width="' + FO.width + '" height="' + FO.height + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' + embHTML + '></embed>';
			}
		}
		else {
			var objAttrHTML = "";
			for (var i = 0; i < UFO.optionalAttrObj.length; i++) {
				if (typeof FO[UFO.optionalAttrObj[i]] != "undefined") {
					objAttrHTML += ' ' + UFO.optionalAttrObj[i] + '="' + FO[UFO.optionalAttrObj[i]] + '"';
				}
			}
			var objParamHTML = "";
			for (var i = 0; i < UFO.optionalAttrParams.length; i++) {
				if (typeof FO[UFO.optionalAttrParams[i]] != "undefined") {
					objParamHTML += '<param name="' + UFO.optionalAttrParams[i] + '" value="' + FO[UFO.optionalAttrParams[i]] + '" />';
				}
			}
			el.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + objAttrHTML + ' width="' + FO.width + '" height="' + FO.height + '" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + FO.majorversion + ',0,' + FO.build + ',0"><param name="movie" value="' + FO.movie + '" />' + objParamHTML + '</object>';
		}
	},

	createModalDialog: function(id) {
		var FO = UFO.foList[id];
		UFO.createStyleRule("html", "height:100%; overflow:hidden;");
		UFO.createStyleRule("body", "height:100%; overflow:hidden;");
		UFO.createStyleRule("#xi-con", "position:absolute; left:0; top:0; z-index:1000; width:100%; height:100%; background-color:#333; filter:alpha(opacity:50); -khtml-opacity:0.5; -moz-opacity:0.5; opacity:0.5;");
		UFO.createStyleRule("#xi-mod", "position:absolute; left:50%; top:50%; margin-left: -" + (parseInt(FO.xiwidth)/2) + "px; margin-top: -" + (parseInt(FO.xiheight)/2) + "px; width:" + FO.xiwidth + "px; height:" + FO.xiheight + "px;");
		var body = document.getElementsByTagName("body")[0];
		var container = UFO.createElement("div");
		container.setAttribute("id", "xi-con");
		var dialog = UFO.createElement("div");
		dialog.setAttribute("id", "xi-mod");
		container.appendChild(dialog);
		body.appendChild(container);
		var MMredirectURL = window.location; // MM code
		document.title = document.title.slice(0, 47) + " - Flash Player Installation"; // MM code
		var MMdoctitle = document.title; // MM code
		if (UFO.is_iewin) {
			var xiFO = { movie:FO.ximovie, width:FO.xiwidth, height:FO.xiheight, majorversion:"6", build:"65", flashvars:"MMredirectURL=" + MMredirectURL + "&amp;MMplayerType=ActiveX&amp;MMdoctitle=" + MMdoctitle };
		}
		else {
			var xiFO = { movie:FO.ximovie, width:FO.xiwidth, height:FO.xiheight, majorversion:"6", build:"65", flashvars:"MMredirectURL=" + MMredirectURL + "&amp;MMplayerType=PlugIn&amp;MMdoctitle=" + MMdoctitle };
		}
		UFO.foList["xi-mod"] = xiFO;
		UFO.writeFlashObject("xi-mod");
	},

	expressInstallCallback: function() {
		var body = document.getElementsByTagName("body")[0];
		var dialog = document.getElementById("xi-con");
	    body.removeChild(dialog);
		UFO.createStyleRule("body", "height:auto; overflow:auto;");
		UFO.createStyleRule("html", "height:auto; overflow:auto;");
	}

};


/*>>>>>>>>>> common.js <<<<<<<<<<*/
// common.js
// javascript functions


_ieversion = 99;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=8)
  _ieversion = 8;
 else if (ieversion>=7)
 _ieversion = 7;
 else if (ieversion>=6)
  _ieversion = 6;
 else if (ieversion>=5)
   _ieversion = 5;
}
   

_objectMoving = "";
_objectMovingIF = "";

_isIE6 = false;
_isIE7 =(_ieversion>=7)?true:false;
_isFOX =(navigator.userAgent.indexOf('Firefox')>=0)?true:false;
_isSafari =(navigator.userAgent.indexOf('Safari')>=0)?true:false;
_isIE = (_isIE6||_isIE7)?true:false;
_callHasSpecialAction = false;

// Add to the string object method for trim(), ltrim and rtrim.
// Exemple: var test = "hello ";
//          test = test.trim();
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function updateButtonClass(amtValue)
{

}

function setCityState(city,state,cityField,stateField)
{
		cityField.value = city;
		stateField.value = state;
}



function _isInteger(val) {
			var digits="1234567890";
			for (var i=0; i < val.length; i++) {
				if (digits.indexOf(val.charAt(i))==-1) { return false; }
				}
			return true;
		}





function openAddress(url, pageWidth, pageHeight, modal, closeCallBack)
{
	
	if(!pageWidth){
		pageWidth = 660;
	}

	if(!pageHeight){
		pageHeight = 400;
	}
	
	if(!modal){
		modal = false;
	}
	
	if(!closeCallBack){
		closeCallBack = "";
	}
	
	
	if($('shopBag'))
	{
		document.body.removeChild($('shopBag'));
	}
	
	j$( '<div class="iframeInnerCtn"><iframe src="' + url + '" width="' + pageWidth + '" height="' + pageHeight + '" frameborder="0"></iframe></div>' ).dialog({
			autoOpen: true 
		,	resize: 'auto'
		,	width: pageWidth
		,	dialogClass: 'iframeOuterCtn'
		,	modal : modal
		,	close: closeCallBack
	});
	
	return false;

	mainDiv = document.createElement('div');
	mainDiv.id = 'addressPopup';
	mainDiv.className = 'addAddress';
	
	overlay = document.createElement('div');
	overlay.className = 'overlayBG';
	mainDiv.appendChild(overlay);
	
	
	iframeEmpty = document.createElement('IFRAME');
	iframeEmpty.className = 'shoppingBagFrameInvisible';
	iframeEmpty.frameBorder = 0;
	iframeEmpty.name = 'iEmpty';
	iframeEmpty.id = 'iShoppingEmpty';
    iframeEmpty.src = '';
				
	mainDiv.appendChild(iframeEmpty);
	
	opaque = document.createElement('div');
	opaque.className = 'opaqueBG';
	mainDiv.appendChild(opaque);

	closeX = document.createElement('input');
	closeX.id = 'windowClose';
	closeX.className = 'button buttonClose';
	closeX.type = 'submit';
	closeX.value = 'x';
	closeX.onclick = closeAddressPopup;
	opaque.appendChild(closeX);
	
	
				
	iframe = document.createElement('IFRAME');
	iframe.className = 'shoppingBagFrame';
	iframe.frameBorder = 0;
	iframe.name = 'iShopping';
	iframe.scrolling = 'yes';
	iframe.id = 'iShopping';
	iframe.src = url;
				
	opaque.appendChild(iframe);
	document.body.appendChild(mainDiv);		
	
	if(document.all&&(_ieversion<7))
	{
		mainDivIF = document.createElement('IFRAME');		
		mainDivIF.id = 'shopBagIF';
		mainDivIF.className = 'shoppingBagContainer';
		mainDivIF.style.display = 'block';	
		mainDivIF.style.border = "0";	
		mainDivIF.scrolling = "no";
		mainDivIF.frameborder = false;	
		
			
		 //<!--- TODO: write javascript function to get css for non included css. current hard coded--->
		mainDivIF.src = siteUrl + "presentationLayer/blank.html";
		mainDivIF.zIndex = parseInt(100000)-1;	
		mainDivIF.style.filter = "alpha(opacity=0)";
		mainDivIF.style.position = 'absolute';
		mainDivIF.style.top = '100px';
		mainDivIF.style.left = '50%';
		mainDivIF.style.padding = '30';
		mainDivIF.frameBorder = false;
		mainDivIF.style.width = parseInt(780);		
		mainDivIF.style.height = parseInt(400)+25;
		mainDivIF.style.width = parseInt(780)+11;
		document.body.appendChild(mainDivIF);		
		
	}			

}

function closeAllDialogs()
{
	j$( ".ui-dialog-content" ).each( function () {
		try {
			j$( this ).dialog( "close" );
		} catch (e) {}
	});
}





function openShoppingBag(totAmount,MinAmount,addtoUrl)
{
    
	if($('shopBag'))
	{
		document.body.removeChild($('shopBag'));
	}
	
	mainDiv = document.createElement('div');
	mainDiv.id = 'shopBag';
	mainDiv.className = 'shoppingBagContainer';
	
	overlay = document.createElement('div');
	overlay.className = 'overlayBG';
	mainDiv.appendChild(overlay);
	
	iframeEmpty = document.createElement('IFRAME');
	iframeEmpty.className = 'shoppingBagFrameInvisible';
	iframeEmpty.frameBorder = 0;
	iframeEmpty.name = 'iEmpty';
	iframeEmpty.id = 'iShoppingEmpty';
    iframeEmpty.src = '';
				
	mainDiv.appendChild(iframeEmpty);
	
	opaque = document.createElement('div');
	opaque.className = 'opaqueBG';
	mainDiv.appendChild(opaque);

	closeX = document.createElement('input');
	closeX.id = 'windowClose';
	closeX.className = 'button buttonClose';
	closeX.type = 'submit';
	closeX.value = 'x';
	closeX.onclick = closeShopBag;
	opaque.appendChild(closeX);
	
	h2Header = document.createElement('h2');
	h2Header.innerHTML = translate.shoppingBag;
	opaque.appendChild(h2Header);	

	minimumOrder = document.createElement('div');
	minimumOrder.id = 'minOrder';
	minimumOrder.className = 'minimumOrder';
	opaque.appendChild(minimumOrder);
	minimumOrder.innerHTML = '';	
	
	orderSumBar = document.createElement('div');
	orderSumBar.id = 'orderSumBar';
		
	tab1 = document.createElement('div');
	tab1.className = 'prodImage';
	tab1.innerHTML = translate.product;
	
	tab2 = document.createElement('div');
	tab2.className = 'prodDesc';
	tab2.innerHTML = '&nbsp';
	
	tab3 = document.createElement('div');
	tab3.className = 'prodColor';
	tab3.innerHTML = translate.color;
	
	tab4 = document.createElement('div');
	tab4.className = 'prodSize';
	tab4.innerHTML = translate.size;
	
	tab5 = document.createElement('div');
	tab5.className = 'prodPrice';
	tab5.innerHTML = translate.price;
	
	tab6 = document.createElement('div');
	tab6.className = 'prodQty';
	tab6.innerHTML = translate.qty;
	
	tab7 = document.createElement('div');
	tab7.className = 'prodTotal';
	tab7.innerHTML = translate.total;
				
	tab8 = document.createElement('div');
	tab8.className = 'prodRemove';
	tab8.innerHTML = '&nbsp;';
				
	orderSumBar.appendChild(tab1);
	orderSumBar.appendChild(tab2);
	orderSumBar.appendChild(tab3);
	orderSumBar.appendChild(tab4);
	orderSumBar.appendChild(tab5);
	orderSumBar.appendChild(tab6);
	orderSumBar.appendChild(tab7);
	orderSumBar.appendChild(tab8);
	opaque.appendChild(orderSumBar);
				
	iframe = document.createElement('IFRAME');
	iframe.className = 'shoppingBagFrame';
	iframe.frameBorder = 0;
	iframe.name = 'iShopping';
	iframe.scrolling = 'yes';
	iframe.id = 'iShopping';
	iframe.src = '/sharedPages/frontEndComponents/specificComponents/b2c/shoppingCart/shoppingCartDetailsPopUp.cfm';
				
	opaque.appendChild(iframe);
	
	
	iframeLogos = document.createElement('IFRAME');
	iframeLogos.className = 'shoppingBagFrameLogos';
	iframeLogos.frameBorder = 0;
	iframeLogos.name = 'iShoppingLogos';
	iframeLogos.scrolling = 'no';
	iframeLogos.id = 'iShoppingLogos';
	iframeLogos.src = '/sharedPages/presentationLayer/baseTemplates/shoppingCart/shoppingCartDetailsLogos.cfm';
				
	opaque.appendChild(iframeLogos);
	
						
	buttonHolder = document.createElement('div');
	buttonHolder.className = 'buttonHolder';
				
	kshopping = document.createElement('BUTTON');
	kshopping.className = 'mainButton';
	kshopping.name = 'keepShopping';
	kshopping.id = 'keepShopping';
	kshopping.innerHTML = translate.keepShopping ;
	kshopping.onclick = closeShopBag;
		
	   if(totAmount >=MinAmount)
	   {
	     pclass='shoppingCartCheckout2';
	   }
	   else
	   {
	     pclass='shoppingCartCheckoutGrey mainButton';
	   }
  
	pcheckOut = document.createElement('BUTTON');
	//pcheckOut.type = 'submit';
	pcheckOut.className = 'mainButton';
	pcheckOut.name = 'checkoutB';
	pcheckOut.id = 'checkoutB';
	pcheckOut.innerHTML = translate.checkout ;
	 
	buttonHolder.appendChild(pcheckOut);
	buttonHolder.appendChild(kshopping);
	
	opaque.appendChild(buttonHolder);
	document.body.appendChild(mainDiv);		
	
	if(document.all&&(_ieversion<7))
	{
		mainDivIF = document.createElement('IFRAME');		
		mainDivIF.id = 'shopBagIF';
		mainDivIF.className = 'shoppingBagContainer';
		mainDivIF.style.display = 'block';	
		mainDivIF.style.border = "0";	
		mainDivIF.scrolling = "no";
		mainDivIF.frameborder = false;	
		
			
		 //<!--- TODO: write javascript function to get css for non included css. current hard coded--->
		mainDivIF.src = siteUrl + "presentationLayer/blank.html";
		mainDivIF.zIndex = parseInt(100000)-1;	
		mainDivIF.style.filter = "alpha(opacity=0)";
		mainDivIF.style.position = 'absolute';
		mainDivIF.style.top = '100px';
		mainDivIF.style.left = '50%';
		mainDivIF.style.padding = '30';
		mainDivIF.frameBorder = false;
		mainDivIF.style.width = parseInt(780);		
		mainDivIF.style.height = parseInt(400)+25;
		mainDivIF.style.width = parseInt(780)+11;
		document.body.appendChild(mainDivIF);		
		
	}			
 
}




function openCoordinatesBag()
{
    
	if($('CoordinatesshopBag'))
	{
		document.body.removeChild($('CoordinatesshopBag'));
	}
	
	mainDiv = document.createElement('div');
	mainDiv.id = 'CoordinatesshopBag';
	mainDiv.className = 'shoppingBagContainer';
	
	overlay = document.createElement('div');
	overlay.className = 'overlayBG';
	mainDiv.appendChild(overlay);
	
	iframeEmpty = document.createElement('IFRAME');
	iframeEmpty.className = 'shoppingBagFrameInvisible';
	iframeEmpty.frameBorder = 0;
	iframeEmpty.name = 'iEmpty';
	iframeEmpty.id = 'iShoppingEmpty';
    iframeEmpty.src = '';
				
	mainDiv.appendChild(iframeEmpty);
	
	opaque = document.createElement('div');
	opaque.className = 'opaqueBG';
	mainDiv.appendChild(opaque);

	closeX = document.createElement('INPUT');
	closeX.id = 'windowClose';
	closeX.className = 'button buttonClose';
	closeX.type = 'submit';
	closeX.value = 'x';
	closeX.onclick = closeCoordinatesshopBag;
	opaque.appendChild(closeX);
	
	h2Header = document.createElement('h2');
	h2Header.innerHTML = translate.coordinatesTitle;
	opaque.appendChild(h2Header);	

	minimumOrder = document.createElement('div');
	minimumOrder.id = 'minOrder';
	minimumOrder.className = 'minimumOrder';
	opaque.appendChild(minimumOrder);
	minimumOrder.innerHTML = '';	
	
	orderSumBar = document.createElement('div');
	orderSumBar.id = 'orderSumBar';
	
	
	tab1 = document.createElement('div');
	tab1.className = 'prodTitle';
	tab1.innerHTML = translate.product;
	
	tab2 = document.createElement('div');
	tab2.className = 'brandTitle';
	tab2.innerHTML = translate.style;
	
	tab3 = document.createElement('div');
	tab3.className = 'colorTitle';
	tab3.innerHTML = translate.color;
	
	tab4 = document.createElement('div');
	tab4.className = 'priceTitle';
	tab4.innerHTML = translate.price;
	
	tab5 = document.createElement('div');
	tab5.className = 'qtyTitle';
	tab5.innerHTML = translate.qty;
	
					
	tab6 = document.createElement('div');
	tab6.className = 'removeTitle';
	tab6.innerHTML = '';
				
	orderSumBar.appendChild(tab1);
	orderSumBar.appendChild(tab2);
	orderSumBar.appendChild(tab3);
	orderSumBar.appendChild(tab4);
	orderSumBar.appendChild(tab5);
	orderSumBar.appendChild(tab6);
	opaque.appendChild(orderSumBar);
				
	iframe = document.createElement('IFRAME');
	iframe.className = 'shoppingBagFrame';
	iframe.frameBorder = 0;
	iframe.name = 'iShopping';
	iframe.id = 'iShopping';
	iframe.src = '/sharedPages/frontEndComponents/specificComponents/b2c/coordinates/coordinatesDetails.cfm';
				
	opaque.appendChild(iframe);
				
	buttonHolder = document.createElement('div');
	buttonHolder.className = 'buttonHolder';
				
	addtobag = document.createElement('BUTTON');
	addtobag.className = 'shoppingCartCheckoutGrey mainButton';
	addtobag.name = 'addToBag';
	addtobag.id = 'addToBag';
	addtobag.innerHTML = 'Add to my bag'+ ' &raquo;';
	addtobag.onclick = closeCoordinatesshopBag;
		
	
	
	buttonHolder.appendChild(addtobag);
	
	opaque.appendChild(buttonHolder);
	document.body.appendChild(mainDiv);				
 
}



function closeShopBag() {
	
	//Fix for Ie7
	hiddenInput = document.createElement('INPUT');
	hiddenInput.type = 'text';
	hiddenInput.id = 'ieFix_hiddenField';
	hiddenInput.style.position = 'absolute';
	hiddenInput.style.top = '-33330px';
	hiddenInput.style.left = '-33330px';
	document.body.appendChild(hiddenInput)
		
	document.body.removeChild($('shopBag'));
	$('ieFix_hiddenField').focus();
	
	if(document.all&&(_ieversion<7))
	{
		document.body.removeChild($('shopBagIF'));
	}
	
}

function closeAddressPopup() {
	
	//Fix for Ie7
	hiddenInput = document.createElement('INPUT');
	hiddenInput.type = 'text';
	hiddenInput.id = 'ieFix_hiddenField';
	hiddenInput.style.position = 'absolute';
	hiddenInput.style.top = '-33330px';
	hiddenInput.style.left = '-33330px';
	document.body.appendChild(hiddenInput)
		
	document.body.removeChild($('addressPopup'));
	$('ieFix_hiddenField').focus();
	
	if(document.all&&(_ieversion<7))
	{
		document.body.removeChild($('shopBagIF'));
	}
	
}


function closeCoordinatesshopBag() {
	

	//Fix for Ie7
	hiddenInput = document.createElement('INPUT');
	hiddenInput.type = 'text';
	hiddenInput.id = 'ieFix_hiddenField';
	hiddenInput.style.position = 'absolute';
	hiddenInput.style.top = '-33330px';
	hiddenInput.style.left = '-33330px';
	document.body.appendChild(hiddenInput)
		
	document.body.removeChild($('CoordinatesshopBag'));
	$('ieFix_hiddenField').focus();
	
	if(document.all&&(_ieversion<7) )
	{
		document.body.removeChild($('shopBagIF'));
	}
	
}



	




boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');

function showBoxAndSetPosition(e,id)
{   
  	for(x=0;x<boxesToClose.length;x++)
  	{
  		hideBox(boxesToClose[x]);
  	}
  	
  //	setLeft = (_isFOX)?e.offsetLeft:getLeftPos(e);
  	
  	//$(id).style.left = e.offsetLeft+'px';
  	
  //	widthAdjust = (_isFOX)?1:-3;
  //	leftAdjust = (_isFOX)?6:9;
  	
  //	$(id).style.left = (setLeft-leftAdjust)+'px';
  //	$(id).style.width = (e.offsetWidth-widthAdjust)+'px';
  	$(id).style.display = 'block';
  	
}

//Used for IE
function getLeftPos(e)
{
	z = 0;
  	myElement = e;
  	while(myElement.tagName != 'BODY')
  	{
  		z+=myElement.offsetLeft;
  		myElement = myElement.parentNode;
  	}
  	
  	return z;
}

function getTopPos(e)
{
	z = 0;
  	myElement = e;
  	while(myElement.tagName != 'BODY')
  	{
  		z+=myElement.offsetTop;
  		myElement = myElement.parentNode;
  	}
  	
  	return z;
}


function hideBox(id)
{   if($(id))
  		$(id).style.display = 'none';
}

var timer;

function ShowShopingCartPopUpDelay(modal)
{
	if(!modal){
		modal = false;
	}

	if($('shoppingBagWindow').style.display != 'block' || modal)
	{
		timer = setTimeout('ShowShopingCartPopUp('+modal+')',300);
	}
}


function ShowShopingCartPopUpDelayGiggle()
{

	if($('shoppingBagWindow').style.display != 'block')
	{
		timer = setTimeout('ShowShopingCartPopUpGiggle()',300);
	}
}

function ShowShopingCartPopUpDelayMyron()
{

	if($('shoppingBagWindow').style.display != 'block')
	{
		timer = setTimeout('ShowShopingCartPopUpMyron()',300);
	}
}

function ShowShopingCartPopClearTimeout()
{
	clearTimeout(timer);
}

function OpenShopPopClearTimeout()
{
    clearTimeout(OpenBoxtimer);
}

function OpenShopPopStartTimeout()
{
    OpenBoxtimer  = setTimeout('CloseShoppingCartPopUp()',300);
}

function ShowShopingCartPopUp(modal)
{	
	if(!modal){
		modal = false;
	}
	
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfo','',modal,ShowShoppingBoxText);	
}

function ShowShopingCartPopUpGiggle()
{	
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfo','',ShowShoppingBoxTextGiggle);	
}

function ShowShopingCartPopUpMyron()
{	
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfoMyron','',ShowShoppingBoxTextMyron);	
}

function getWinWidth() {
	if (window.innerWidth) {
		return window.innerWidth;
		} 
	else if (document.body.clientWidth) {
		return document.body.clientWidth;
		} 
	else {
		return 100;
	}
}

function ShowShoppingBoxText(result)
{
   OpenBoxtimer  = setTimeout('CloseShoppingCartPopUp()',3500);
   boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');
   for(x=0;x<boxesToClose.length;x++)
 	{
 		hideBox(boxesToClose[x]);
 	}
   
	showCountObj = $('ShoppingBagInfoLine');
	
	
	if (result[0].AMOUNT != '0')
	{
		//Check if id=topShoppingCart Class Should be changed
		if(typeof changeCartClass != 'undefined')
		changecss(); // This function is located in topNavigation.cfm
		
		if($('ShippingBagLineItems'))
			$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
		
		if (result[0].MODAL == 'true')
		{
			var args = {
					message: j$('#shoppingBagWindowContainer').html()
				,	cssClass: 'shoppingBagWindowModal'
				,	hideCloseBtn: true
				,	closeOtherDialogs: true
			};
			
			g_ShowModal=true;
			showAlert(args);
			$('shoppingBagWindow').style.display = 'block';
			
		}
		else
		{
			if($('shoppingBagWindow'))
				$('shoppingBagWindow').style.display = 'block';
		}
		
		//showBoxAndSetPosition(passE,passId);	
	}		

		leftVal = getWinWidth()/2;

		if($('shoppingBagWindow'))
			$('shoppingBagWindow').style.left = leftVal + "px";	
}

function ShowShoppingBoxTextGiggle(result)
{
   boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');
   for(x=0;x<boxesToClose.length;x++)
 	{
 		hideBox(boxesToClose[x]);
 	}
   
	showCountObj = $('ShoppingBagInfoLine');
	
	
	showCountObj.innerHTML = result[0].AMOUNT + ' ' +result[0].ITEMTEXT;
	
	if (result[0].AMOUNT != '0')
	{
		if($('ShippingBagLineItems'))
			$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
		
		if($('shoppingBagWindow'))
			$('shoppingBagWindow').style.display = 'block';
		//showBoxAndSetPosition(passE,passId);	
		timer=setTimeout("CloseShoppingCartPopUp()", 5000);
	}		

	
		if($('shoppingBagWindow'))
			$('shoppingBagWindow').style.left = "700px";	
}

function ShowShoppingBoxTextMyron(result)
{
   boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');
   for(x=0;x<boxesToClose.length;x++)
 	{
 		hideBox(boxesToClose[x]);
 	}
   
	showCountObj = $('ShoppingBagInfoLine');
	showCountObj.innerHTML = result[0].AMOUNT + ' ' +result[0].ITEMTEXT;
	
	if (result[0].AMOUNT != '0')
	{
		$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
		$('topShoppingCart').className = 'active';
		$('shoppingBagWindow').style.display = 'block';
		//showBoxAndSetPosition(passE,passId);	
	}		

		//leftVal = getWinWidth()/2;

		//$('shoppingBagWindow').style.left = leftVal + "px";	
}


function changeClassName(theitem, NewclassName) {
  if((document.getElementById(theitem).className != NewclassName)) {
    document.getElementById(theitem).className = NewclassName;
  } else {
    document.getElementById(theitem).className = '';
  }
}

function toggleOneItem(theitem) {
  if((document.getElementById(theitem).style.display == 'block') || (document.getElementById(theitem).style.display == -1))
  	{
    document.getElementById(theitem).style.display = 'none';
    document.getElementById('invisibleFrame').style.display = 'none';
    }
  else
    document.getElementById(theitem).style.display = 'block';
}


function openWindow(theURL,w,h) {
  posx=(screen.availWidth-w)/2;
  posy=(screen.availHeight-h)/2;
  window.open(theURL,'popup','toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable=yes'+',width='+w+',height='+h+',left='+posx+',top='+posy);
}

function getPageScroll(){

	var yScroll, arrayPageScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll, pageHeight, pageWidth, arrayPageSize;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function findClassProperties(style,rule)
{
	styles = document.styleSheets;
	for(x=0;x<styles.length;x++)
	{
		href = styles[x].href;
	
		if(href.indexOf(window.location.hostname) >= 0 && href.indexOf(style))	
		{
			rules = (styles[x].rules)?styles[x].rules:styles[x].cssRules;
			
			for(zz=0;zz<rules.length;zz++)
			{
				temp1 = rules[zz];
				temp2 = rule;
					
				if(temp1.type!=3)
				{	
					if(temp1.selectorText.toUpperCase() == rule.toUpperCase())
					{
						return rules[zz];	
					}		
					
				}	
			}									
		}			
	}
}

_cssClass = "";

function showAlert(obj) {
			
	var url, message, targetAlert, cssClass, closeBText, hideCloseBtn, closeOtherDialogs, closeOnEscape;
	
	url = (obj.url === undefined)?'':obj.url;
	message = (obj.message === undefined)?'':obj.message;
	targetAlert = (obj.target === undefined)?'alertbox':obj.target;	
	cssClass = (obj.cssClass === undefined)?'alertbox':obj.cssClass;
	/*closeBText = (obj.closeBText === undefined)?'Close X':obj.closeBText;*/
	closeBText = (obj.closeBText === undefined)?'Close X':'Close X';
	hideCloseBtn = (obj.hideCloseBtn === undefined)?false:obj.hideCloseBtn;
	closeOtherDialogs = (obj.closeOtherDialogs === undefined)?true:obj.closeOtherDialogs;
	closeOnEscape = (obj.closeOnEscape === undefined)?true:obj.closeOnEscape;
	
	if(typeof parent.startLoading !== undefined ) 
		parent.startLoading = true;
	
	var args = {
			MESSAGE: message
		,	URL: url
		,	CLOSEBUTTONTEXT: closeBText
		,	TEMPLATE: 1
		,	DIVID: targetAlert
		,	CSSCLASS: cssClass
		,	HIDECLOSEBTN: hideCloseBtn
		,	CLOSEOTHERDIALOGS: closeOtherDialogs
		,	CLOSEONESCAPE: closeOnEscape
		
	};
	
	if ( message != "" ) {
		
		args.PARAMS = args;
		
		args.CONTENT = message;
		
		callText_Result( args );
				
	} else {
	
		j$.post(
				siteUrl + "/com/b2c/genericProxy.cfc?returnFormat=json&method=getText"
			,	args
			,	callText_Result
			,	"json"
		);

	}
	
}

function showPopUp(obj) {
			
	/* function emptied as unused, see rev. 106781 for previous code */
}




function callText_Result(result)
{

	try{
		result.CONTENT = decodeURIComponent( result.CONTENT );
	} catch(e) {}
	
	if ( result.CLOSEOTHERDIALOGS ) {
		j$( ".ui-dialog-content" ).each( function () {
			try {
				j$( this ).dialog( "close" );
			} catch (e) {}
		});
	}
	
	var jAlert = j$("<div id='" + result.PARAMS.DIVID + "' class='" + result.PARAMS.CSSCLASS + "'></div>").html( result.CONTENT ).appendTo( "body" ).hide();
	
	jAlert.dialog({
			width: jAlert.css( "width" )
		,	autoOpen: true
		,	modal: true
		,	closeText: result.PARAMS.CLOSEBUTTONTEXT
		,   closeOnEscape: result.PARAMS.CLOSEONESCAPE
	});
	
	if ( result.PARAMS.HIDECLOSEBTN )
		jAlert.parent().find( ".ui-dialog-titlebar" ).hide();
	
	if(_callHasSpecialAction)
	{
		eval(_callHasSpecialAction);
		_callHasSpecialAction = null;
	}			
		
	if(typeof parent.startLoading !== undefined ) 
		parent.startLoading = false;
}

function killAlertBox(divID,divIF)
{

	if (!divID || divID == '')
	{
		document.body.removeChild(_objectMoving);
		if(document.all&&(_ieversion<7))
		{
				document.body.removeChild(_objectMovingIF);			
		}	
	}
	else
	{
		DivObj = document.getElementById(divID);
		document.body.removeChild(DivObj);
     
     		
		if(document.all&&(_ieversion<7))
		{
			DivIFObj = document.getElementById(divID+'IF');
			document.body.removeChild(DivIFObj);
		}
	

     }
							
}					

lineCount = 0;
lastDrop = 2;
normCount = 1;


function deleteClone(o,msg)
{

	AmountOfRows = document.getElementById("lineItemsHolder").getElementsByTagName('DIV');
	
	countRows = 0;
	//lineCount--;
	for(i=0;i<AmountOfRows.length;i++)
	{
		if(AmountOfRows[i].id.indexOf('lineItem_color_') >= 0)
		{
			countRows++;
		}
	}
	
	

	if (countRows > 1)
	{
		count = parseInt(o.id.split('_')[1]);
		TopParent = document.getElementById("lineItemsHolder"); 
		
		ColorChild = document.getElementById("lineItem_color_"+count); 
		SizeChild = document.getElementById("lineItem_size_"+count); 
		QtyChild = document.getElementById("lineItem_qty_"+count); 
		
		TopParent.removeChild(ColorChild);
		TopParent.removeChild(SizeChild);
		TopParent.removeChild(QtyChild);
	}
	else
	{
		showAlert({message:msg,closeBText:'x',cssClass:'alertboxSmall'});
	}
}

function cloneItemLine(o)
{
	count = parseInt(o.id.split('_')[1]);
	idCount = lastDrop + 1;
	lineCount++
	
	//Color	
	toClone = $('lineItem_color_'+count).cloneNode(true);
	toCloneInner = toClone.innerHTML;
	
	toCloneInner = 	setDropDownObjects(toCloneInner,'color-',count,idCount,lineCount);
	
	
	
	div1 = document.createElement('DIV');
	div1.id = 'lineItem_color_'+normCount;	
	div1.className = 'selectBlock'; 
	div1.innerHTML = toCloneInner;
	
	
	$('lineItemsHolder').appendChild(div1);

	//_listMenus.addMember('menuWrap_'+idCount);
			
	//_listMenus.assignEvent("dropDownColorActions('colorId-"+lineCount+"');",idCount);
	
	//menuColorWrapId = idCount;
	
	//Size
	toClone = $('lineItem_size_'+count).cloneNode(true);
	toCloneInner = toClone.innerHTML;
	idCount = parseInt(idCount)+1;
	
	
	toCloneInner = 	setDropDownObjects(toCloneInner,'SizeSelectBox-',count,idCount,lineCount);
	
	div2 = document.createElement('DIV');
	div2.id = 'lineItem_size_'+normCount;
	div2.className = 'selectBlock'; 
	div2.innerHTML = toCloneInner;
	$('lineItemsHolder').appendChild(div2);

	//_listMenus.addMember('menuWrap_'+idCount);
	
	//Qty
	toClone = $('lineItem_qty_'+count).cloneNode(true);
	toCloneInner = toClone.innerHTML;
	
	idCount = parseInt(idCount)+1;
	
	toCloneInner = 	setDropDownObjects(toCloneInner,'itemQuantity-',count,idCount,lineCount);
	
	
	addImg = 'add_' + count;
	addImgNew = 'add_' + normCount;
	toCloneInner = toCloneInner.replace(addImg,addImgNew);
	
	minusImg = 'minus_' + count;
	minusImgNew = 'minus_' + normCount;
	toCloneInner = toCloneInner.replace(minusImg,minusImgNew);
	
	div3 = document.createElement('DIV');
	div3.id = 'lineItem_qty_'+normCount;
	div3.className = 'selectBlock'; 
	div3.innerHTML = toCloneInner;
	
	$('lineItemsHolder').appendChild(div3);
	//_listMenus.addMember('menuWrap_'+idCount);
	
	//_affect = 'SizeSelectBox-'+lineCount;
	//_resultKeys = new Array('SKU_ID','SIZE_DESC');
	//_res = new Array();
	//dropDownSetRelation(_res);
	
	//setCurrentMenu($('menuSelect_'+menuColorWrapId));
	//selectMenu($('colorId-'+lineCount+'_0'))
	
	normCount++;
	lastDrop +=3;
	
	 
}

function setDropDownObjects(str,valObj,c,idc,seq){
	
	//str = str.replace('menuWrap_'+c,'menuWrap_'+idc);
	//str = str.replace('menuSelect_'+c,'menuSelect_'+idc);
	//str = str.replace('menuHeader_'+c,'menuHeader_'+idc);
	//str = str.replace('menuArrow_'+c,'menuArrow_'+idc);
	//str = str.replace('color-'+c,'color-'+idc);
	//str = str.replace('add_'+c,'add_'+idc);
	
	RXstr = valObj+count;
	str = str.replace(eval('/'+RXstr+'/g'),valObj+seq);
	
	str = str.replace(/_listMenus./g,'//_listMenus.');
	
	return str;
}

_itemId = '';

bypassZoom = false;




// Color and size drop down relation 
//onRadioColorClick
function dropDownColorActions(img_value)
{
	//alert(tempId);
	//alert(img_value);
	img_value = img_value.split('|');
	img_ColorID	= img_value[0];
	img_price	= img_value[1];
	img_priceOnSale = img_value[2];
	if(img_value[4]) img_memberprice = img_value[4];
	if(img_value!='' && img_value[8]){
		lineNumber = img_value[8].split('-')[1];
	}else{
		lineNumber = '';
	}
	if(img_value[5]) convertPrice=img_value[5];
	if(img_value[6]) convertPriceONSale=img_value[6];
	if(img_value[7]) convertPriceMember=img_value[7];
	
	if(img_value!='')
	{
		//alert(translate.ourprice);
		priceDescription = ''
		convertDescription = ''
		priceDescription = img_price;
		if(img_priceOnSale != ''){
			priceDescription = priceDescription + ' |' + img_priceOnSale;
		}
		if(img_value[5]) convertDescription=convertDescription+'( '+convertPrice;
		if(img_value[6]) convertDescription=convertDescription+' | '+convertPriceONSale;
		if(img_value[7]) convertDescription=convertDescription+' | '+convertPriceMember;
		if(img_value[5]) convertDescription=convertDescription+' )';
		
		if($("isNewInd"))
		{
			if ($("isNewInd").value == 'Y') {
				if (img_priceOnSale != '') 
					img_priceOnSale = img_priceOnSale + ' |';
				img_priceOnSale = img_priceOnSale + ' NEW';
			}
		}
		
		
		if($("productPrice"))
		{
			$("productPrice").innerHTML =img_price;
		}
		
		if($("productPriceonsale"))
		{
			if(img_priceOnSale != ''){
				//$("productPriceonsale").innerHTML =' | ' +img_priceOnSale;
				$("productPriceonsale").innerHTML = img_priceOnSale; // OSH Version NO Pipe
			} else {
				$("productPriceonsale").innerHTML = '';
			}	
		}
		
		if($("Price") && priceDescription)
		{
			$("Price").innerHTML =priceDescription;
		}
		
		if($("memberPrice") && img_memberprice)
		{
			$("memberPrice").innerHTML =img_memberprice;
		}
		
		if($("convertPrice") && convertDescription)
		{
			$("convertPrice").innerHTML =convertDescription;
		}		
		
		bypassImageZoomer = false;
		bypassImageZoomer =	bypassZoom;
		bypassZoom = false;
		if(_itemId=='')
		{
			_itemId = img_value[3];
			//bypassImageZoomer = true;
		}	

		if($("lineColorSelected"))
		{
			$("lineColorSelected").value =lineNumber;
		}

		//getSizesDetails(img_ColorID,_itemId);
		getDimensionsDetails(img_ColorID,_itemId);
	    if(!bypassImageZoomer)
	    {	
			setImageZoomer();	
		}	
		else
		{
			setImageForNoFlash();
		}
	}	
}


function dropDownColorFromQuickView(idx)
{
	img_value	= $(idx).value;

	img_value = img_value.split('|');
	img_ColorID	= img_value[0];
	img_price	= img_value[1];
	
	if(img_value[8]) convertPrice=img_value[8];
	if(img_value[9]) convertPriceONSale=img_value[9];
	if(img_value[10]) convertPriceMember=img_value[10];
	
	if($(idx).value != '' && $(idx).value != '0')
	{
		relationId = $(idx).id.split('-')[1];
		
		
		if(img_value[2]!='' && img_value[2] != '0.00')
		 {
		  img_priceOnSale	= '| <span class="sale">$'+img_value[2]+' '+ $('SaleText').value  +'</span>';
		 }
		 else
		 {
		 	img_priceOnSale	= '';
		 }
		 
		 if($("newproduct").value == 'Y' && img_priceOnSale == '')
		 {
		 	if($('actualCurLang').value == 'fre')
		 		isNew = '| NOUVEAU';
		 	else
				isNew = '| NEW';
		 }
		 else
		 {
		 	isNew = '';
		 }
		
		
		if($("ItemPriceValueID"))
		{
			$("ItemPriceValueID").innerHTML = '$'+ img_price +' '+img_priceOnSale + ' ' + isNew;
			if(img_value[7]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+'<br>'+img_value[7];
			
			
			
			if(img_value[8]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+'<br> ( '+convertPrice;
			if(img_value[9]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+' | '+convertPriceONSale;
			if(img_value[10]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+' | '+convertPriceMember;
			if(img_value[8]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+' ) ';
		}
		
		_itemId = $('itemID').value;	
		
		getSizesQuickView(img_ColorID,_itemId);
		
	}
	else
	{

		$('colorId-0').value = '';
		
	}	
	
}


 function getSizesQuickView(colorId,itemId)
{
	DWREngine._execute(_cfCatLevelsLocation, null, 'getSizesByColorItem',itemId,colorId,updateSelectQuickView_result);
}


function updateSelectQuickView_result(result)
{
	_resultKeys = new Array('SKU_ID','SIZE_DESC');	
	dropDownSetRelation(result);
	setColorIMageQuickView();
}

function dropDownColorFromList(idx)
{
	img_name 	= $(idx).name;
	img_value	= $(idx).value;

	img_name = img_name.split('_');
	img_rowID = img_name[1];
	img_value = img_value.split('|');
	img_ColorID	= img_value[0];
	img_price	= img_value[1];
	
	
	if(img_value[8]) convertPrice=img_value[8];
	if(img_value[9]) convertPriceONSale=img_value[9];
	if(img_value[10]) convertPriceMember=img_value[10];
	
	if($(idx).value != '' && $(idx).value != '0')
	{
		relationId = $(idx).id.split('-')[1];
		j$("#tdPrice_" + img_rowID).html(img_price);
		
		_itemId = $('itemID_' + img_rowID).value;	
		getSizesFromList(img_ColorID,_itemId,img_rowID);
		
	}
	else
	{

		$(img_name).value = '';
		
	}	

}

 function getSizesFromList(colorId,itemId,rowId)
{
	DWREngine._execute(_cfCatLevelsLocation, null, 'getSizesByColorItemRow',itemId,colorId,rowId,updateSelectFromList_result);
}

function updateSelectFromList_result(result)
{
	var rowId = result[0].ROW_ID;
	var sb = $("SizeSelectBox_" + rowId);
	
	if ( sb.options.length == 0 || sb.options[ 0 ].value != "" )
		initialLength = 0;
	else
		initialLength = 1;
	
	// Clear the current drop down box value
	$("SizeSelectBox_" + rowId).options.length = initialLength;
    // alert(result);
	// Build drop down box here.
	for ( i=0; i < result.length; i++ )
	{
		addToSizeDropDown = true;

		if (result[i].INSTOCK == 'false')
		{
			sizeTEXT = result[i].SIZE_DESC + ' (Out of Stock)';
			addToSizeDropDown = false;
		}
		else
		{
			sizeTEXT = result[i].SIZE_DESC;
		}



		if(addToSizeDropDown)
		{
				optObj = new Option(sizeTEXT, result[i].SKU_ID, false);
				// Append the new option...
				sb.options[i+initialLength] = optObj;

				if(result.length == 1)
				{
					tempText = sb.options[initialLength].text;
					j$('#singleSize_' + rowId).html(tempText);
					if (tempText.indexOf('Out of Stock') < 0)
						sb.selectedIndex = initialLength;

					if($('singleSize_' + rowId))
					{
						sb.style.display = 'none';
						$('singleSize_' + rowId).style.display = 'block';
					}
				}
				else
				{
					if($('singleSize_' + rowId))
					{
						if(sb.style.display == 'none')
						{
							sb.style.display = 'block';
							$('singleSize_' + rowId).style.display = 'none';
						}
						
					}
				}
				
				if(result[i].PRICE){
				sb.options[i+initialLength].id = result[i].PRICE + '~' + result[i].TEMPSALEPRICE;
				}else {
				sb.options[i+initialLength].id = '';	
				}

		}
		



	}
}


function setColorIMageQuickView(){	

	if (img_value[5] == '')
	{
		$('productImageQV').src = '/static/webupload/730/noImg_3.jpg';
	}
	else
	{
 		$('productImageQV').src = '/_static/webupload/731/'+img_value[5];
	}
}

function FocusNextField(CurrentFieldname, NextFieldName, ActivateLength)
{
	currentField = document.getElementById(CurrentFieldname);
	nextField = document.getElementById(NextFieldName);
	
	if(currentField){
		if(currentField.value.length == ActivateLength){	
			if(nextField){		
				nextField.focus();
			}	
		}	
	}
}

function changeLanguageUrlRewrite(lang)
{
	urlPath = window.location.href;
 	urlPath = urlPath.toString();
 	
 	
 	if (lang == 'eng')
 	{
 		if(urlPath.indexOf('/eng/') > -1)
	 		urlPath = urlPath.replace('/eng/','/fre/');
	 	else
	 	{
	 		if(urlPath.indexOf('lang=eng') > -1)
	 			urlPath = urlPath.replace('lang=eng','lang=fre');
	 		else
	 		{
	 			if(urlPath.indexOf('?') > -1)
	 				urlPath = urlPath + '&lang=fre';
	 			else
	 				urlPath = urlPath + '?lang=fre';
	 		}
	 			
	 	}
	 }
	else
	{
		if(urlPath.indexOf('/fre/') > -1)
			urlPath = urlPath.replace('/fre/','/eng/');	
		else
	 	{
	 		if(urlPath.indexOf('lang=fre') > -1)
	 			urlPath = urlPath.replace('lang=fre','lang=eng');
	 		else
	 		{
	 			if(urlPath.indexOf('?') > -1)
	 				urlPath = urlPath + '&lang=eng';
	 			else
	 				urlPath = urlPath + '?lang=eng';
	 		}
	 	}
	}
		
	window.location.href = urlPath;
}


function showQuickView(o,direct)
{

	img = o.getElementsByTagName('IMG');
	divId = o.id.split('_')[1];
	imgExists = (img.length > 0)?true:false;
	
	divClassName = $('d_'+divId).className;
	if (_isFOX) {
		setLeft = (_isFOX)?o.offsetLeft:getLeftPos(o);
		setTop = (_isFOX)?o.offsetTop:getTopPos(o);
	} else {
		setLeft = (_isSafari)?o.offsetLeft:getLeftPos(o);
		setTop = (_isSafari)?o.offsetTop:getTopPos(o);
	}
	
	
	if(direct.toUpperCase()=='SHOW')
	{
		if(imgExists){img[0].className = 'opaque';}
		
		/*IMG_WIDTH = img[0].width;
		IMG_HEIGHT = img[0].height;
		//170
		//debug($('q_'+divId))
		
		BTN_WIDTH = $('q_dummy').width;
		BTN_HEIGHT = $('q_dummy').height;
		
		
		adjustLeft = Math.ceil((IMG_WIDTH/2)-(BTN_WIDTH/2));
		adjustTop = Math.ceil((IMG_WIDTH/2));
		
		
		$('d_'+divId).style.left = (setLeft+adjustLeft)+'px';
		$('d_'+divId).style.top = (setTop+adjustTop)+'px';*/
		$('d_'+divId).className = divClassName.replace('displayNone','displayBlock'); 
	}
	else
	{
		if(imgExists){img[0].className = '';}
		$('d_'+divId).className = divClassName.replace('displayBlock','displayNone');
	}
}


  	
  	/*
  	
  	widthAdjust = (_isFOX)?1:-3;
  	leftAdjust = (_isFOX)?6:9;
  	
  	$(id).style.left = (setLeft-leftAdjust)+'px';
  	$(id).style.width = (e.offsetWidth-widthAdjust)+'px';
  	$(id).style.display = 'block';

*/
	
	function showreturnPolicy(url)
	{
		showAlert({url:url,target:'returnsAlertBOX',cssClass:'alertboxCVC'});
	}
	
		function ThousandSeparator(decimalDigits,Value)
		{
		     // Separator Length. Here this is thousand separator
		     var separatorLength = 3;
		     var OriginalValue=Value;
		     var TempValue = "" + OriginalValue;
		     var NewValue = "";
		
		      // Store digits after decimal
		      var pStr;
		
		      // store digits before decimal
		      var dStr;
		
		      // Add decimal point if it is not there
		      if (TempValue.indexOf(".")==-1)
		     {
		           TempValue+="."
		     }
		
		    dStr=TempValue.substr(0,TempValue.indexOf("."));
		
		    pStr=TempValue.substr(TempValue.indexOf("."))
		
		    // Add 0 for remaining digits after decimal point
		    while (pStr.length-1< decimalDigits){pStr+="0"}
		
		    if(pStr ==".")
		            pStr =""; 
		   
		   if(dStr.length > separatorLength)
		  {
		        // Logic of separation
		       while( dStr.length > separatorLength)
		      {
		              NewValue = "," + dStr.substr(dStr.length - separatorLength) + NewValue;
		             dStr = dStr.substr(0,dStr.length - separatorLength);
		       }
		       NewValue = dStr + NewValue;
		   }
		   else
		  {
		       NewValue = dStr;
		   }
		   // Add decimal part
		   NewValue = NewValue + pStr;
			
			return NewValue;
		  } 
		  
function setQASCountry(cID){
	
	var country='CAN';
	if ($(cID).value=='US')
		country='USA';
	if ($(cID).value=='UK')	
		country='GBR';
		
	if($('COUNTRYSET'))	
		$('COUNTRYSET').value =country;
		//alert($('COUNTRYSET').value);
} 		  


function changeCountryProvice(cID){
	var countryId = "";
	if (cID != null)
		countryId = $(cID).value;
	else
		countryId = $('countryID').value;
	
	if (countryId == "CA")
    {
		$('shprovince').options[0]=new Option('select province','OO');
    }
	else if (countryId == "US")
    {
		$('shprovince').options[0]=new Option('select state','OO');
    }
	else
	{
		$('shprovince').options[0]=new Option('other','OO');
	}	
	
	DWREngine._execute(_cfCatLevelsLocation, null, 'callGetStates',countryId,'#variables.actualLang#',changeCountryProvice_result);

	if (cID != null)
		countryIdVar=cID;
    else
		countryIdVar='countryID';
}
function reloadPage(obj){
if(! eval(obj.options[obj.selectedIndex].value))
window.location.reload();
}

function updateNumberChildrenDropDownList(){
var childNumber = eval(document.getElementById('allChildrens').getElementsByTagName('div').length +1);
document.getElementById('Children').options[childNumber].selected = true;
if (childNumber < 11)document.getElementById('plusButton').style.display = 'block';
document.getElementById('numberChildren').value=childNumber-1;
}

function addBlocChildren(){
var allChildrens = document.getElementById('allChildrens');
var childNumber = eval(allChildrens.getElementsByTagName('div').length +1);

document.getElementById('numberChildren').value=childNumber;
if (childNumber < 11) {
var modelChild = document.getElementById('allChildrens').getElementsByTagName('div')[0].innerHTML;
var newChild = document.createElement('div');
modelChild = modelChild.replace(/child_name_1/gi,'child_name_'+childNumber);
modelChild = modelChild.replace(/blocChild_1/gi,'blocChild_'+childNumber);

modelChild = modelChild.replace(/BirthYearChild_1/gi,'BirthYearChild_'+childNumber);
modelChild = modelChild.replace(/BirthMonthChild_1/gi,'BirthMonthChild_'+childNumber);
modelChild = modelChild.replace(/BirthDayChild_1/gi,'BirthDayChild_'+childNumber);
modelChild = modelChild.replace(/genderChild_1/gi,'genderChild_'+childNumber);
modelChild = modelChild.replace(/child 1/gi,'Child '+childNumber);
modelChild = modelChild.replace(/updateInd_1/gi,'updateInd_'+childNumber);
modelChild = modelChild.replace(/user_child_id_1/gi,'user_child_id_'+childNumber);
modelChild = modelChild.replace(/selected/gi,'');
newChild.innerHTML = modelChild;
allChildrens.appendChild(newChild);
document.getElementById('updateInd_'+childNumber).value='i';
document.getElementById('child_name_'+childNumber).value='';
document.getElementById('Children').options[childNumber+1].selected = true;

document.getElementById('plusButton').style.display = 'none';


}
}

function changeCountryProvice_result(result){
  
	
	
  if(result.length==0){
  	 $('shprovince').options.length = 1;
     //$('shprovince').options[1]=new Option('Other','OO');
  } else{
  	 $('shprovince').options.length = 1;
    for (i=0; i<result.length; i++) {

		$('shprovince').options[i+1] = new Option(result[i].NAME,result[i].STATE_ID);
	}
  }
  
  if($('COUNTRYSET')!= null)
	  setQASCountry(countryIdVar);

}

function updateStateOptions ( obj, field ) {
	
	var data = {
			method: "getStates"
		,	countryID: j$( obj ).val()
		,	stateDD: field
	};
	
	j$.post(
			siteUrl + "com/b2c/genericproxy.cfc?returnformat=json"
		,	data
		,	updateStateOptions_result
		,	"json"
	);
}

function updateStateOptions_result ( r ) {
	
	var jStateDD = j$( "#" + r.STATEDD );
	var state;
	
	if ( jStateDD.length == 0 )
		return false;
	
	jStateDD.find( "option[value!='']" ).remove();
	
	for ( var i=0; i<r.ASTATES.length; i++ ) {
		
		state = r.ASTATES[ i ];
		
		jStateDD.append( "<option value='" + state.STATE_ID + "'>" + state.NAME + "</option>" );
		
	}
	
	jStateDD.each( function () {
		this.options.selectedIndex = 0;
	});
	
}

		  
	function CurrencyFormatted(amount)
	{
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	}
	
	function CurrencyFormattedComma(amount)
	{
		amount = String(amount);
		
		var delimiter = ","; // replace comma if desired
		var a = amount.split('.',2)
		var d = a[1];
		var i = parseInt(a[0]);
		if(isNaN(i)) { return ''; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		if(n.length > 0) { a.unshift(n); }
		n = a.join(delimiter);
		if(d.length < 1) { amount = n; }
		else { amount = n + '.' + d; }
		amount = minus + amount;
		return amount;
	}		  

function enforceReadonlyDropDowns ( filter ) {

	/* make sure readonly dropdowns can't be modified */
	if ( filter )
		var jDropdowns = filter.find( "select[ readonly ]" );
	else
		var jDropdowns = j$( "select[ readonly ]" );
	
	jDropdowns.each( function () {
		j$( this ).data( "previousValue", j$( this ).val() );
		j$( this ).data( "onchange", j$( this ).attr( "onchange" ) );
		j$( this ).removeAttr( "onchange" );
		j$( this ).unbind( "change" );
	});
	
	jDropdowns.change( function () {
		j$( this ).val( j$( this ).data( "previousValue" ) );
	});
	
};

function resetReadonlyDropdowns ( filter ) {
	
	/* reset readonly dropdowns to their initial state */
	if ( filter )
		var jDropdowns = filter.find( "select[ readonly ]" );
	else
		var jDropdowns = j$( "select[ readonly ]" );
	
	jDropdowns.unbind( "change" );
	
	jDropdowns.each( function () {
		j$( this ).change( j$( this ).data( "onchange" ) );
	});
	
};

//use this function to replace any element with a processing image, and return it to it's previous state (through the use of the action parameter
function toggleButtonInProgress ( buttonID, action ) {
	
	var jButton = j$( "#" + buttonID );
	
	if ( jButton.length ) {
	
		switch ( action ) {
		
			case "hide":
				
				var data = {
						original: jButton.html()
					,	width: jButton.css( "width" )
					,	height: jButton.css( "height" )
					,	background: jButton.css( "background" )
				};
				
				jButton.data( "toggleButton", data ).css({
						width: jButton.width()
					,	height: jButton.height()
					,	background: "url(" + g_imageInProgress + ") no-repeat center center"
				}).empty();
				
				break;
			
			case "show":
				
				var data = jButton.data( "toggleButton" );
				
				jButton.css({
						width: data.width
					,	height: data.height
					,	background: data.background
				}).html( data.original );
				
				break;
				
		}
		
	}
	
}

function addToRegistry() {

	var skuID = j$( "#giftRegistrySKU_ID" ).val();
	var quantity = j$( "#giftRegistryQuantity" ).val();

	if ( quantity == "" )
		quantity = 1;
	
	if ( skuID == "" )
		showAlert({ message: msg_addToRegistrySelectColorSize });
	else {
		
		var data = {
				method: "addSKUToRegistry"
			,	returnFormat: "json"
			,	skuID: skuID
			,	quantity: quantity
		};
		
		j$.post(
				siteUrl + "/com/b2c/shoppingcart-proxy.cfc"
			,	data
			,	function ( r ) {
					if ( r.SUCCESS ) {
						refreshRegistryToolbar( r.TOOLBARINFO );
						showAlert({ message: msg_skuAddedToRegistry_success });
					} else
						showAlert({ message: msg_skuAddedToRegistry_error });
				}
			,	"json"	
		);
		
	}
	
}

function refreshRegistryToolbar ( toolbarInfo ) {
	
	// if the toolbarInfo isn't passed in, we need to go get it
	if ( toolbarInfo === undefined ) {
		
		j$.post(
			siteUrl + "/com/b2c/shoppingcart-proxy.cfc"
			,	"method=getRegistrySummary&returnformat=json"
			,	refreshRegistryToolbar
			,	"json"	
		);
		
	}
	
	if ( toolbarInfo.REGISTRY_ID == "" ) {
		j$( "#registryToolbarLastItemEmpty" ).show();
		j$( "#registryToolbarLastItemFull" ).hide();
	} else {
		
		j$( "#registryToolbarQtyRequested" ).html( toolbarInfo.QTY_REQUESTED );
		j$( "#registryToolbarQtyOrdered" ).html( toolbarInfo.QTY_ORDERED );

		j$( "#registryToolbarLastItemDescription" ).html( toolbarInfo.LASTITEMDETAILS.DESCRIPTION );
		j$( "#registryToolbarLastItemPrice" ).html( toolbarInfo.LASTITEMDETAILS.PERMANENT_PRICE );
		j$( "#registrySummaryLastItemQuantity" ).html( toolbarInfo.LAST_QTY_REQUESTED );
		
		var jImage = j$( "#registryToolbarLastItemImage" );
		
		var src = jImage.attr( "src" ).match( /^(.+?)[^/]*$/i )[1];
		
		
		jImage.attr( "alt", toolbarInfo.LASTITEMDETAILS.DESCRIPTION ).attr( "src", src + toolbarInfo.LASTITEMDETAILS.IMAGE_2 );
		
		if ( toolbarInfo.LASTITEMDETAILS.COLOR != "" ) {
			j$( "#registryToolbarLastItemColor" ).html( toolbarInfo.LASTITEMDETAILS.COLOR ).parent().show();
		} else
			j$( "#registryToolbarLastItemColor" ).parent().hide();

		if ( toolbarInfo.LASTITEMDETAILS.DIMENSION != "" ) {
			j$( "#registryToolbarLastItemDimension" ).html( toolbarInfo.LASTITEMDETAILS.DIMENSION ).parent().show();
		} else
			j$( "#registryToolbarLastItemDimension" ).parent().hide();

		if ( toolbarInfo.LASTITEMDETAILS.SIZE != "" ) {
			j$( "#registryToolbarLastItemSize" ).html( toolbarInfo.LASTITEMDETAILS.SIZE ).parent().show();
		} else
			j$( "#registryToolbarLastItemSize" ).parent().hide();
		
		j$( "#registryToolbarLastItemEmpty" ).hide();
		j$( "#registryToolbarLastItemFull" ).show();
	}
	
}

function __IsValidEmailMask(email)
{

	filter = /^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$/

		if (filter.test(email))
		{
			return true;
		}
		else
		{
			return false;
		}
}

function isValidPhoneMask(phone){
	filter = /^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$/
	return filter.test(phone);
}

function trackFromRefererTag(refererTag,url)
	{
		DWREngine._execute(_cfCatLevelsLocation, null, 'trackFromRefererTag',refererTag,url,trackFromRefererTag_result);
	}
	
	function trackFromRefererTag_result(result)
	{
		document.location.href = result;
	}
	
		  		
function init()
{
	DWREngine._errorHandler =  errorHandler;
}

function CloseShopingCartPopUpDelay(time)
{
	if(!time){
		time = 2000;
	}	
	timer = setTimeout('CloseShoppingCartPopUp()',time);
}


function startScroll(direction) 
{
	runwayScrolling = true; 
	scrollRunway(direction); 
}

function scrollRunway(direction)
{
	if(runwayScrolling)
	{
		document.getElementById('runwaySpace').scrollLeft+= direction;
		setTimeout("scrollRunway(" + direction + ")",1);
	}
}

function stopScroll() 
{ 
	runwayScrolling = false; 
}


function formatCurrency(amount) {
	
	var i = parseFloat(amount);
	
	if(isNaN(i)) { i = 0.00; }
	
	var minus = '';
	
	if(i < 0) { minus = '-'; }
	
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	
	if(s.indexOf('.') < 0) { s += '.00'; }
	
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	
	s = minus + '$' + s;
	
	return s;

}





function submitNewsletterSignup(myUrl, formId) 
{
	$(formId).action = myUrl;
	$(formId).submit();
}



function CheckNewsLetterUserExists(actionUrl, emailId, emailInvalidMessage, aEmailAlreadyMessage, aLoginLink, aFormId)
{
	var UserEmail = j$('#' + emailId).val().trim();
	if(__IsValidEmailMask(UserEmail))
	{
		var args = {method:'CheckUserInscDetails',email:UserEmail, actionUrl:actionUrl, emailAlreadyMessage:aEmailAlreadyMessage, loginLink:aLoginLink, formId: aFormId};
		j$.ajax({
		              url: siteUrl + "com/b2c/newsletter.cfc?returnformat=json"
		       ,      data: args
		       ,      success: CheckNewsLetterUserExists_Result
		       ,      dataType: "json"
		       ,      TYPE: "GET"
		});
	} 
	else
	{
		showAlert({message:emailInvalidMessage,cssClass:'fieldEmpty'});
	}     
  }
 
	  
function CheckNewsLetterUserExists_Result(r)
{    
	if (r.EXISTS && r.HASACCOUNT)
	{//User Has Account
		LoginLink = r.LOGINLINK;
		
		window.location.href = LoginLink;
		return false;
	}
	else if(!r.EXISTS)
	{//User does Not Exist
		submitNewsletterSignup(r.ACTIONURL, r.FORMID);
	}
	else
	{//Exists but does not have an account.
		var RegistMsg = r.EMAILALREADYMESSAGE;
		showAlert({message:RegistMsg,cssClass:'fieldEmpty'});
		return false;
	}//if Exists Ends
}




init();

/*>>>>>>>>>> jquery-1.4.2.min.js <<<<<<<<<<*/
/*!
 * jQuery JavaScript Library v1.4.2
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sat Feb 13 22:33:48 2010 -0500
 */
(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);

//no conflict declaration

j$ = jQuery.noConflict();

/*>>>>>>>>>> dump.js <<<<<<<<<<*/
// Class: Dump
// Author: Shuns (www.netgrow.com.au/files)
// Last Updated: 10/10/06
// Version: 1.08

dump=function(object, showTypes){var dump='';var st=typeof showTypes=='undefined' ? true : showTypes;var winName='dumpWin';var browser=_dumpIdentifyBrowser();var w=760;var h=500;var leftPos=screen.width ?(screen.width-w)/ 2 : 0;var topPos=screen.height ?(screen.height-h)/ 2 : 0;var settings='height='+h+',width='+w+',top='+topPos+',left='+leftPos+',scrollbars=yes,menubar=yes,status=yes,resizable=yes';var title='Dump';var script='function tRow(s){t=s.parentNode.lastChild;tTarget(t, tSource(s));}function tTable(s){var switchToState=tSource(s);var table=s.parentNode.parentNode;for(var i=1;i < table.childNodes.length;i++){t=table.childNodes[i];if(t.style){tTarget(t, switchToState);}}}function tSource(s){if(s.style.fontStyle=="italic"||s.style.fontStyle==null){s.style.fontStyle="normal";s.title="click to collapse";return "open";}else{s.style.fontStyle="italic";s.title="click to expand";return "closed";}}function tTarget(t, switchToState){if(switchToState=="open"){t.style.display="";}else{t.style.display="none";}}';dump+=(/string|number|undefined|boolean/.test(typeof(object))||object==null)? object : recurse(object, typeof object);winName=window.open('', winName, settings);if(browser.indexOf('ie')!=-1||browser=='opera'||browser=='ie5mac'||browser=='safari'){winName.document.write('<html><head><title> '+title+' </title><script type="text/javascript">'+script+'</script><head>');winName.document.write('<body>'+dump+'</body></html>');}else{winName.document.body.innerHTML=dump;winName.document.title=title;var ffs=winName.document.createElement('script');ffs.setAttribute('type', 'text/javascript');ffs.appendChild(document.createTextNode(script));winName.document.getElementsByTagName('head')[0].appendChild(ffs);}winName.focus();function recurse(o, type){var i;var j=0;var r='';type=_dumpType(o);switch(type){case 'regexp':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>RegExp: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'date':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>Date: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'function':var t=type;var a=o.toString().match(/^.*function.*?\((.*?)\)/im);var args=(a==null||typeof a[1]=='undefined'||a[1]=='')? 'none' : a[1];r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td colspan="2"'+_dumpStyles(t,'td-value')+'><table'+_dumpStyles('arguments','table')+'><tr><td'+_dumpStyles('arguments','td-key')+'><i>Arguments: </i></td><td'+_dumpStyles(type,'td-value')+'>'+args+'</td></tr><tr><td'+_dumpStyles('arguments','td-key')+'><i>Function: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o+'</td></tr></table>';j++;break;case 'domelement':var t=type;r+='<table'+_dumpStyles(t,'table')+'><tr><th colspan="2"'+_dumpStyles(t,'th')+'>'+t+'</th></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Name: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeName.toLowerCase()+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Type: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeType+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>Node Value: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.nodeValue+'</td></tr>';r+='<tr><td'+_dumpStyles(t,'td-key')+'><i>innerHTML: </i></td><td'+_dumpStyles(type,'td-value')+'>'+o.innerHTML+'</td></tr>';j++;break;}if(/object|array/.test(type)){for(i in o){var t=typeof o[i];if(j < 1){r+='<table'+_dumpStyles(type,'table')+'><tr><th colspan="2"'+_dumpStyles(type,'th')+'>'+type+'</th></tr>';j++;}if(typeof o[i]=='object' && o[i]!=null){if(_dumpType(o[i]=='domelement')){t='domelement';r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? '['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}else{r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? '['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}}else if(typeof o[i]=='function'){r+='<tr><td'+_dumpStyles(type ,'td-key')+'>'+i+(st ? '['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+recurse(o[i], t)+'</td></tr>';}else{r+='<tr><td'+_dumpStyles(type,'td-key')+'>'+i+(st ? '['+t+']' : '')+'</td><td'+_dumpStyles(type,'td-value')+'>'+o[i]+'</td></tr>';}}}if(j==0){r+='<table'+_dumpStyles(type,'table')+'><tr><th colspan="2"'+_dumpStyles(type,'th')+'>'+type+'[empty]</th></tr>';}r+='</table>';return r;};};_dumpStyles=function(type, use){var r='';var table='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;cell-spacing:2px;';var th='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;text-align:left;color: white;padding: 5px;vertical-align :top;cursor:hand;cursor:pointer;';var td='font-size:xx-small;font-family:verdana,arial,helvetica,sans-serif;vertical-align:top;padding:3px;';var thScript='onClick="tTable(this);" title="click to collapse"';var tdScript='onClick="tRow(this);" title="click to collapse"';switch(type){case 'string':case 'number':case 'boolean':case 'undefined':case 'object':switch(use){case 'table':r=' style="'+table+'background-color:#0000cc;"';break;case 'th':r=' style="'+th+'background-color:#4444cc;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#ccddff;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'array':switch(use){case 'table':r=' style="'+table+'background-color:#006600;"';break;case 'th':r=' style="'+th+'background-color:#009900;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#ccffcc;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'function':switch(use){case 'table':r=' style="'+table+'background-color:#aa4400;"';break;case 'th':r=' style="'+th+'background-color:#cc6600;"'+thScript;break;case 'td-key':r=' style="'+td+'background-color:#fff;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'arguments':switch(use){case 'table':r=' style="'+table+'background-color:#dddddd;cell-spacing:3;"';break;case 'td-key':r=' style="'+th+'background-color:#eeeeee;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;}break;case 'regexp':switch(use){case 'table':r=' style="'+table+'background-color:#CC0000;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#FF0000;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#FF5757;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'date':switch(use){case 'table':r=' style="'+table+'background-color:#663399;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#9966CC;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#B266FF;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;case 'domelement':switch(use){case 'table':r=' style="'+table+'background-color:#FFCC33;cell-spacing:3;"';break;case 'th':r=' style="'+th+'background-color:#FFD966;"'+thScript;break;case 'td-key':r=' style="'+th+'background-color:#FFF2CC;color:#000000;cursor:hand;cursor:pointer;"'+tdScript;break;case 'td-value':r=' style="'+td+'background-color:#fff;"';break;}break;}return r;};_dumpIdentifyBrowser=function(){var agent=navigator.userAgent.toLowerCase();if (typeof window.opera != 'undefined'){return 'opera';} else if (typeof document.all != 'undefined'){if (typeof document.getElementById != 'undefined'){var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, '$1').replace(/ /, '');if(typeof document.uniqueID != 'undefined') {if (browser.indexOf('5.5') != -1){return browser.replace(/(.*5\.5).*/, '$1');}else{return browser.replace(/(.*)\..*/, '$1');}}else{return 'ie5mac';}}}else if(typeof document.getElementById != 'undefined'){if (navigator.vendor.indexOf('Apple Computer, Inc.')!=-1) {return 'safari';}else if(agent.indexOf('gecko')!=-1) {return 'mozilla';}}return false;};_dumpType=function(obj){var t=typeof(obj);if(t=='function'){var f=obj.toString();if((/^\/.*\/[gi]??[gi]??$/).test(f)){return 'regexp';}else if((/^\[object.*\]$/i).test(f)){t='object'}}if(t !='object'){return t;}switch(obj){case null:return 'null';case window:return 'window';case document:return document;case window.event:return 'event';}if(window.event &&(event.type==obj.type)){return 'event';}var c=obj.constructor;if(c !=null){switch(c){case Array:t='array';break;case Date:return 'date';case RegExp:return 'regexp';case Object:t='object';break;case ReferenceError:return 'error';default:var sc=c.toString();var m=sc.match(/\s*function(.*)\(/);if(m !=null){return 'object';}}}var nt=obj.nodeType;if(nt !=null){switch(nt){case 1:if(obj.item==null){return 'domelement';}break;case 3:return 'string';}}if(obj.toString !=null){var ex=obj.toString();var am=ex.match(/^\[object(.*)\]$/i);if(am !=null){var am=am[1];switch(am.toLowerCase()){case 'event':return 'event';case 'nodelist':case 'htmlcollection':case 'elementarray':return 'array';case 'htmldocument':return 'htmldocument';}}}return t;};

/*>>>>>>>>>> jquery-ui-1.7.2.min.js <<<<<<<<<<*/
/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.2",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;/*
 * jQuery UI Dialog 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function(c){var b={dragStart:"start.draggable",drag:"drag.draggable",dragStop:"stop.draggable",maxHeight:"maxHeight.resizable",minHeight:"minHeight.resizable",maxWidth:"maxWidth.resizable",minWidth:"minWidth.resizable",resizeStart:"start.resizable",resize:"drag.resizable",resizeStop:"stop.resizable"},a="ui-dialog ui-widget ui-widget-content ui-corner-all ";c.widget("ui.dialog",{_init:function(){this.originalTitle=this.element.attr("title");var l=this,m=this.options,j=m.title||this.originalTitle||"&nbsp;",e=c.ui.dialog.getTitleId(this.element),k=(this.uiDialog=c("<div/>")).appendTo(document.body).hide().addClass(a+m.dialogClass).css({position:"absolute",overflow:"hidden",zIndex:m.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(n){(m.closeOnEscape&&n.keyCode&&n.keyCode==c.ui.keyCode.ESCAPE&&l.close(n))}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(n){l.moveToTop(false,n)}),g=this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(k),f=(this.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(k),i=c('<a href="#"/>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){i.addClass("ui-state-hover")},function(){i.removeClass("ui-state-hover")}).focus(function(){i.addClass("ui-state-focus")}).blur(function(){i.removeClass("ui-state-focus")}).mousedown(function(n){n.stopPropagation()}).click(function(n){l.close(n);return false}).appendTo(f),h=(this.uiDialogTitlebarCloseText=c("<span/>")).addClass("ui-icon ui-icon-closethick").text(m.closeText).appendTo(i),d=c("<span/>").addClass("ui-dialog-title").attr("id",e).html(j).prependTo(f);f.find("*").add(f).disableSelection();(m.draggable&&c.fn.draggable&&this._makeDraggable());(m.resizable&&c.fn.resizable&&this._makeResizable());this._createButtons(m.buttons);this._isOpen=false;(m.bgiframe&&c.fn.bgiframe&&k.bgiframe());(m.autoOpen&&this.open())},destroy:function(){(this.overlay&&this.overlay.destroy());this.uiDialog.hide();this.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");this.uiDialog.remove();(this.originalTitle&&this.element.attr("title",this.originalTitle))},close:function(f){var d=this;if(false===d._trigger("beforeclose",f)){return}(d.overlay&&d.overlay.destroy());d.uiDialog.unbind("keypress.ui-dialog");(d.options.hide?d.uiDialog.hide(d.options.hide,function(){d._trigger("close",f)}):d.uiDialog.hide()&&d._trigger("close",f));c.ui.dialog.overlay.resize();d._isOpen=false;if(d.options.modal){var e=0;c(".ui-dialog").each(function(){if(this!=d.uiDialog[0]){e=Math.max(e,c(this).css("z-index"))}});c.ui.dialog.maxZ=e}},isOpen:function(){return this._isOpen},moveToTop:function(f,e){if((this.options.modal&&!f)||(!this.options.stack&&!this.options.modal)){return this._trigger("focus",e)}if(this.options.zIndex>c.ui.dialog.maxZ){c.ui.dialog.maxZ=this.options.zIndex}(this.overlay&&this.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=++c.ui.dialog.maxZ));var d={scrollTop:this.element.attr("scrollTop"),scrollLeft:this.element.attr("scrollLeft")};this.uiDialog.css("z-index",++c.ui.dialog.maxZ);this.element.attr(d);this._trigger("focus",e)},open:function(){if(this._isOpen){return}var e=this.options,d=this.uiDialog;this.overlay=e.modal?new c.ui.dialog.overlay(this):null;(d.next().length&&d.appendTo("body"));this._size();this._position(e.position);d.show(e.show);this.moveToTop(true);(e.modal&&d.bind("keypress.ui-dialog",function(h){if(h.keyCode!=c.ui.keyCode.TAB){return}var g=c(":tabbable",this),i=g.filter(":first")[0],f=g.filter(":last")[0];if(h.target==f&&!h.shiftKey){setTimeout(function(){i.focus()},1)}else{if(h.target==i&&h.shiftKey){setTimeout(function(){f.focus()},1)}}}));c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();this._trigger("open");this._isOpen=true},_createButtons:function(g){var f=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");this.uiDialog.find(".ui-dialog-buttonpane").remove();(typeof g=="object"&&g!==null&&c.each(g,function(){return !(d=true)}));if(d){c.each(g,function(h,i){c('<button type="button"></button>').addClass("ui-state-default ui-corner-all").text(h).click(function(){i.apply(f.element[0],arguments)}).hover(function(){c(this).addClass("ui-state-hover")},function(){c(this).removeClass("ui-state-hover")}).focus(function(){c(this).addClass("ui-state-focus")}).blur(function(){c(this).removeClass("ui-state-focus")}).appendTo(e)});e.appendTo(this.uiDialog)}},_makeDraggable:function(){var d=this,f=this.options,e;this.uiDialog.draggable({cancel:".ui-dialog-content",handle:".ui-dialog-titlebar",containment:"document",start:function(){e=f.height;c(this).height(c(this).height()).addClass("ui-dialog-dragging");(f.dragStart&&f.dragStart.apply(d.element[0],arguments))},drag:function(){(f.drag&&f.drag.apply(d.element[0],arguments))},stop:function(){c(this).removeClass("ui-dialog-dragging").height(e);(f.dragStop&&f.dragStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}})},_makeResizable:function(g){g=(g===undefined?this.options.resizable:g);var d=this,f=this.options,e=typeof g=="string"?g:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",alsoResize:this.element,maxWidth:f.maxWidth,maxHeight:f.maxHeight,minWidth:f.minWidth,minHeight:f.minHeight,start:function(){c(this).addClass("ui-dialog-resizing");(f.resizeStart&&f.resizeStart.apply(d.element[0],arguments))},resize:function(){(f.resize&&f.resize.apply(d.element[0],arguments))},handles:e,stop:function(){c(this).removeClass("ui-dialog-resizing");f.height=c(this).height();f.width=c(this).width();(f.resizeStop&&f.resizeStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}}).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_position:function(i){var e=c(window),f=c(document),g=f.scrollTop(),d=f.scrollLeft(),h=g;if(c.inArray(i,["center","top","right","bottom","left"])>=0){i=[i=="right"||i=="left"?i:"center",i=="top"||i=="bottom"?i:"middle"]}if(i.constructor!=Array){i=["center","middle"]}if(i[0].constructor==Number){d+=i[0]}else{switch(i[0]){case"left":d+=0;break;case"right":d+=e.width()-this.uiDialog.outerWidth();break;default:case"center":d+=(e.width()-this.uiDialog.outerWidth())/2}}if(i[1].constructor==Number){g+=i[1]}else{switch(i[1]){case"top":g+=0;break;case"bottom":g+=e.height()-this.uiDialog.outerHeight();break;default:case"middle":g+=(e.height()-this.uiDialog.outerHeight())/2}}g=Math.max(g,h);this.uiDialog.css({top:g,left:d})},_setData:function(e,f){(b[e]&&this.uiDialog.data(b[e],f));switch(e){case"buttons":this._createButtons(f);break;case"closeText":this.uiDialogTitlebarCloseText.text(f);break;case"dialogClass":this.uiDialog.removeClass(this.options.dialogClass).addClass(a+f);break;case"draggable":(f?this._makeDraggable():this.uiDialog.draggable("destroy"));break;case"height":this.uiDialog.height(f);break;case"position":this._position(f);break;case"resizable":var d=this.uiDialog,g=this.uiDialog.is(":data(resizable)");(g&&!f&&d.resizable("destroy"));(g&&typeof f=="string"&&d.resizable("option","handles",f));(g||this._makeResizable(f));break;case"title":c(".ui-dialog-title",this.uiDialogTitlebar).html(f||"&nbsp;");break;case"width":this.uiDialog.width(f);break}c.widget.prototype._setData.apply(this,arguments)},_size:function(){var e=this.options;this.element.css({height:0,minHeight:0,width:"auto"});var d=this.uiDialog.css({height:"auto",width:e.width}).height();this.element.css({minHeight:Math.max(e.minHeight-d,0),height:e.height=="auto"?"auto":Math.max(e.height-d,0)})}});c.extend(c.ui.dialog,{version:"1.7.2",defaults:{autoOpen:true,bgiframe:false,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1000},getter:"isOpen",uuid:0,maxZ:0,getTitleId:function(d){return"ui-dialog-title-"+(d.attr("id")||++this.uuid)},overlay:function(d){this.$el=c.ui.dialog.overlay.create(d)}});c.extend(c.ui.dialog.overlay,{instances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(d){return d+".dialog-overlay"}).join(" "),create:function(e){if(this.instances.length===0){setTimeout(function(){if(c.ui.dialog.overlay.instances.length){c(document).bind(c.ui.dialog.overlay.events,function(f){var g=c(f.target).parents(".ui-dialog").css("zIndex")||0;return(g>c.ui.dialog.overlay.maxZ)})}},1);c(document).bind("keydown.dialog-overlay",function(f){(e.options.closeOnEscape&&f.keyCode&&f.keyCode==c.ui.keyCode.ESCAPE&&e.close(f))});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var d=c("<div></div>").appendTo(document.body).addClass("ui-widget-overlay").css({width:this.width(),height:this.height()});(e.options.bgiframe&&c.fn.bgiframe&&d.bgiframe());this.instances.push(d);return d},destroy:function(d){this.instances.splice(c.inArray(this.instances,d),1);if(this.instances.length===0){c([document,window]).unbind(".dialog-overlay")}d.remove();var e=0;c.each(this.instances,function(){e=Math.max(e,this.css("z-index"))});this.maxZ=e},height:function(){if(c.browser.msie&&c.browser.version<7){var e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var d=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(e<d){return c(window).height()+"px"}else{return e+"px"}}else{return c(document).height()+"px"}},width:function(){if(c.browser.msie&&c.browser.version<7){var d=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);var e=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(d<e){return c(window).width()+"px"}else{return d+"px"}}else{return c(document).width()+"px"}},resize:function(){var d=c([]);c.each(c.ui.dialog.overlay.instances,function(){d=d.add(this)});d.css({width:0,height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);;/*
 * jQuery UI Datepicker 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */
(function($){$.extend($.ui,{datepicker:{version:"1.7.2"}});var PROP_NAME="datepicker";function Datepicker(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],dateFormat:"mm/dd/yy",firstDay:0,isRTL:false};this._defaults={showOn:"focus",showAnim:"show",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,showMonthAfterYear:false,yearRange:"-10:+10",showOtherMonths:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"normal",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false};$.extend(this._defaults,this.regional[""]);this.dpDiv=$('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",log:function(){if(this.debug){console.log.apply("",arguments)}},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase();var inline=(nodeName=="div"||nodeName=="span");if(!target.id){target.id="dp"+(++this.uuid)}var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{});if(nodeName=="input"){this._connectDatepicker(target,inst)}else{if(inline){this._inlineDatepicker(target,inst)}}},_newInst:function(target,inline){var id=target[0].id.replace(/([:\[\]\.])/g,"\\\\$1");return{id:id,input:target,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:inline,dpDiv:(!inline?this.dpDiv:$('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}},_connectDatepicker:function(target,inst){var input=$(target);inst.append=$([]);inst.trigger=$([]);if(input.hasClass(this.markerClassName)){return}var appendText=this._get(inst,"appendText");var isRTL=this._get(inst,"isRTL");if(appendText){inst.append=$('<span class="'+this._appendClass+'">'+appendText+"</span>");input[isRTL?"before":"after"](inst.append)}var showOn=this._get(inst,"showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){var buttonText=this._get(inst,"buttonText");var buttonImage=this._get(inst,"buttonImage");inst.trigger=$(this._get(inst,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText}):$('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage==""?buttonText:$("<img/>").attr({src:buttonImage,alt:buttonText,title:buttonText})));input[isRTL?"before":"after"](inst.trigger);inst.trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==target){$.datepicker._hideDatepicker()}else{$.datepicker._showDatepicker(target)}return false})}input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst)},_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return}divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst);this._setDate(inst,this._getDefaultDate(inst));this._updateDatepicker(inst);this._updateAlternate(inst)},_dialogDatepicker:function(input,dateText,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){var id="dp"+(++this.uuid);this._dialogInput=$('<input type="text" id="'+id+'" size="1" style="position: absolute; top: -100px;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],PROP_NAME,inst)}extendRemove(inst.settings,settings||{});this._dialogInput.val(dateText);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var browserHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",this._pos[0]+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv)}$.data(this._dialogInput[0],PROP_NAME,inst);return this},_destroyDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();$.removeData(target,PROP_NAME);if(nodeName=="input"){inst.append.remove();inst.trigger.remove();$target.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress)}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}},_enableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=false;inst.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=true;inst.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[this._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_getInst:function(target){try{return $.data(target,PROP_NAME)}catch(err){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(target,name,value){var inst=this._getInst(target);if(arguments.length==2&&typeof name=="string"){return(name=="defaults"?$.extend({},$.datepicker._defaults):(inst?(name=="all"?$.extend({},inst.settings):this._get(inst,name)):null))}var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}if(inst){if(this._curInst==inst){this._hideDatepicker(null)}var date=this._getDateDatepicker(target);extendRemove(inst.settings,settings);this._setDateDatepicker(target,date);this._updateDatepicker(inst)}},_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value)},_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date,endDate){var inst=this._getInst(target);if(inst){this._setDate(inst,date,endDate);this._updateDatepicker(inst);this._updateAlternate(inst)}},_getDateDatepicker:function(target){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst)}return(inst?this._getDate(inst):null)},_doKeyDown:function(event){var inst=$.datepicker._getInst(event.target);var handled=true;var isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker(null,"");break;case 13:var sel=$("td."+$.datepicker._dayOverClass+", td."+$.datepicker._currentClass,inst.dpDiv);if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0])}else{$.datepicker._hideDatepicker(null,$.datepicker._get(inst,"duration"))}return false;break;case 27:$.datepicker._hideDatepicker(null,$.datepicker._get(inst,"duration"));break;case 33:$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M");break;case 34:$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M");break;case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target)}handled=event.ctrlKey||event.metaKey;break;case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target)}handled=event.ctrlKey||event.metaKey;break;case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?+1:-1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M")}break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D")}handled=event.ctrlKey||event.metaKey;break;case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?-1:+1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M")}break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,+7,"D")}handled=event.ctrlKey||event.metaKey;break;default:handled=false}}else{if(event.keyCode==36&&event.ctrlKey){$.datepicker._showDatepicker(this)}else{handled=false}}if(handled){event.preventDefault();event.stopPropagation()}},_doKeyPress:function(event){var inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){var chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));var chr=String.fromCharCode(event.charCode==undefined?event.keyCode:event.charCode);return event.ctrlKey||(chr<" "||!chars||chars.indexOf(chr)>-1)}},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return}var inst=$.datepicker._getInst(input);var beforeShow=$.datepicker._get(inst,"beforeShow");extendRemove(inst.settings,(beforeShow?beforeShow.apply(input,[input,inst]):{}));$.datepicker._hideDatepicker(null,"");$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed";return !isFixed});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}var offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;inst.rangeStart=null;inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute")),display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){var showAnim=$.datepicker._get(inst,"showAnim")||"show";var duration=$.datepicker._get(inst,"duration");var postProcess=function(){$.datepicker._datepickerShowing=true;if($.browser.msie&&parseInt($.browser.version,10)<7){$("iframe.ui-datepicker-cover").css({width:inst.dpDiv.width()+4,height:inst.dpDiv.height()+4})}};if($.effects&&$.effects[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[showAnim](duration,postProcess)}if(duration==""){postProcess()}if(inst.input[0].type!="hidden"){inst.input[0].focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){var dims={width:inst.dpDiv.width()+4,height:inst.dpDiv.height()+4};var self=this;inst.dpDiv.empty().append(this._generateHTML(inst)).find("iframe.ui-datepicker-cover").css({width:dims.width,height:dims.height}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout",function(){$(this).removeClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).removeClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).removeClass("ui-datepicker-next-hover")}}).bind("mouseover",function(){if(!self._isDisabledDatepicker(inst.inline?inst.dpDiv.parent()[0]:inst.input[0])){$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");$(this).addClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).addClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).addClass("ui-datepicker-next-hover")}}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();var numMonths=this._getNumberOfMonths(inst);var cols=numMonths[1];var width=17;if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",(width*cols)+"em")}else{inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("")}inst.dpDiv[(numMonths[0]!=1||numMonths[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst.input&&inst.input[0].type!="hidden"&&inst==$.datepicker._curInst){$(inst.input[0]).focus()}},_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth();var dpHeight=inst.dpDiv.outerHeight();var inputWidth=inst.input?inst.input.outerWidth():0;var inputHeight=inst.input?inst.input.outerHeight():0;var viewWidth=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)+$(document).scrollLeft();var viewHeight=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)+$(document).scrollTop();offset.left-=(this._get(inst,"isRTL")?(dpWidth-inputWidth):0);offset.left-=(isFixed&&offset.left==inst.input.offset().left)?$(document).scrollLeft():0;offset.top-=(isFixed&&offset.top==(inst.input.offset().top+inputHeight))?$(document).scrollTop():0;offset.left-=(offset.left+dpWidth>viewWidth&&viewWidth>dpWidth)?Math.abs(offset.left+dpWidth-viewWidth):0;offset.top-=(offset.top+dpHeight>viewHeight&&viewHeight>dpHeight)?Math.abs(offset.top+dpHeight+inputHeight*2-viewHeight):0;return offset},_findPos:function(obj){while(obj&&(obj.type=="hidden"||obj.nodeType!=1)){obj=obj.nextSibling}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input,duration){var inst=this._curInst;if(!inst||(input&&inst!=$.data(input,PROP_NAME))){return}if(inst.stayOpen){this._selectDate("#"+inst.id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear))}inst.stayOpen=false;if(this._datepickerShowing){duration=(duration!=null?duration:this._get(inst,"duration"));var showAnim=this._get(inst,"showAnim");var postProcess=function(){$.datepicker._tidyDialog(inst)};if(duration!=""&&$.effects&&$.effects[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[(duration==""?"hide":(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide")))](duration,postProcess)}if(duration==""){this._tidyDialog(inst)}var onClose=this._get(inst,"onClose");if(onClose){onClose.apply((inst.input?inst.input[0]:null),[(inst.input?inst.input.val():""),inst])}this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv)}}this._inDialog=false}this._curInst=null},_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(event){if(!$.datepicker._curInst){return}var $target=$(event.target);if(($target.parents("#"+$.datepicker._mainDivId).length==0)&&!$target.hasClass($.datepicker.markerClassName)&&!$target.hasClass($.datepicker._triggerClass)&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)){$.datepicker._hideDatepicker(null,"")}},_adjustDate:function(id,offset,period){var target=$(id);var inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return}this._adjustInstDate(inst,offset+(period=="M"?this._get(inst,"showCurrentAtPos"):0),period);this._updateDatepicker(inst)},_gotoToday:function(id){var target=$(id);var inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear}else{var date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear()}this._notifyChange(inst);this._adjustDate(target)},_selectMonthYear:function(id,select,period){var target=$(id);var inst=this._getInst(target[0]);inst._selectingMonthYear=false;inst["selected"+(period=="M"?"Month":"Year")]=inst["draw"+(period=="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target)},_clickMonthYear:function(id){var target=$(id);var inst=this._getInst(target[0]);if(inst.input&&inst._selectingMonthYear&&!$.browser.msie){inst.input[0].focus()}inst._selectingMonthYear=!inst._selectingMonthYear},_selectDay:function(id,month,year,td){var target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return}var inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=$("a",td).html();inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;if(inst.stayOpen){inst.endDay=inst.endMonth=inst.endYear=null}this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear));if(inst.stayOpen){inst.rangeStart=this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay));this._updateDatepicker(inst)}},_clearDate:function(id){var target=$(id);var inst=this._getInst(target[0]);inst.stayOpen=false;inst.endDay=inst.endMonth=inst.endYear=inst.rangeStart=null;this._selectDate(target,"")},_selectDate:function(id,dateStr){var target=$(id);var inst=this._getInst(target[0]);dateStr=(dateStr!=null?dateStr:this._formatDate(inst));if(inst.input){inst.input.val(dateStr)}this._updateAlternate(inst);var onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{if(inst.input){inst.input.trigger("change")}}if(inst.inline){this._updateDatepicker(inst)}else{if(!inst.stayOpen){this._hideDatepicker(null,this._get(inst,"duration"));this._lastInput=inst.input[0];if(typeof(inst.input[0])!="object"){inst.input[0].focus()}this._lastInput=null}}},_updateAlternate:function(inst){var altField=this._get(inst,"altField");if(altField){var altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");var date=this._getDate(inst);dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(altField).each(function(){$(this).val(dateStr)})}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getFullYear(),date.getMonth(),date.getDate());var firstMon=new Date(checkDate.getFullYear(),1-1,4);var firstDay=firstMon.getDay()||7;firstMon.setDate(firstMon.getDate()+1-firstDay);if(firstDay<4&&checkDate<firstMon){checkDate.setDate(checkDate.getDate()-3);return $.datepicker.iso8601Week(checkDate)}else{if(checkDate>new Date(checkDate.getFullYear(),12-1,28)){firstDay=new Date(checkDate.getFullYear()+1,1-1,4).getDay()||7;if(firstDay>4&&(checkDate.getDay()||7)<firstDay-3){return 1}}}return Math.floor(((checkDate-firstMon)/86400000)/7)+1},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var doy=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){lookAhead(match);var origSize=(match=="@"?14:(match=="y"?4:(match=="o"?3:2)));var size=origSize;var num=0;while(size>0&&iValue<value.length&&value.charAt(iValue)>="0"&&value.charAt(iValue)<="9"){num=num*10+parseInt(value.charAt(iValue++),10);size--}if(size==origSize){throw"Missing number at position "+iValue}return num};var getName=function(match,shortNames,longNames){var names=(lookAhead(match)?longNames:shortNames);var size=0;for(var j=0;j<names.length;j++){size=Math.max(size,names[j].length)}var name="";var iInit=iValue;while(size>0&&iValue<value.length){name+=value.charAt(iValue++);for(var i=0;i<names.length;i++){if(name==names[i]){return i+1}}size--}throw"Unknown name at position "+iInit};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"o":doy=getNumber("o");break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"@":var date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(year==-1){year=new Date().getFullYear()}else{if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}}if(doy>-1){month=1;day=doy;do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}var date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TIMESTAMP:"@",W3C:"yy-mm-dd",formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num}}return num};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate(),2);break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"o":var doy=date.getDate();for(var m=date.getMonth()-1;m>=0;m--){doy+=this._getDaysInMonth(date.getFullYear(),m)}output+=formatNumber("o",doy,3);break;case"m":output+=formatNumber("m",date.getMonth()+1,2);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"@":output+=date.getTime();break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":case"m":case"y":case"@":chars+="0123456789";break;case"D":case"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars},_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name]},_setDateFromField:function(inst){var dateFormat=this._get(inst,"dateFormat");var dates=inst.input?inst.input.val():null;inst.endDay=inst.endMonth=inst.endYear=null;var date=defaultDate=this._getDefaultDate(inst);var settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate}catch(event){this.log(event);date=defaultDate}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=(dates?date.getDate():0);inst.currentMonth=(dates?date.getMonth():0);inst.currentYear=(dates?date.getFullYear():0);this._adjustInstDate(inst)},_getDefaultDate:function(inst){var date=this._determineDate(this._get(inst,"defaultDate"),new Date());var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);return date},_determineDate:function(date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset,getDaysInMonth){var date=new Date();var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();var pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;var matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case"d":case"D":day+=parseInt(matches[1],10);break;case"w":case"W":day+=parseInt(matches[1],10)*7;break;case"m":case"M":month+=parseInt(matches[1],10);day=Math.min(day,getDaysInMonth(year,month));break;case"y":case"Y":year+=parseInt(matches[1],10);day=Math.min(day,getDaysInMonth(year,month));break}matches=pattern.exec(offset)}return new Date(year,month,day)};date=(date==null?defaultDate:(typeof date=="string"?offsetString(date,this._getDaysInMonth):(typeof date=="number"?(isNaN(date)?defaultDate:offsetNumeric(date)):date)));date=(date&&date.toString()=="Invalid Date"?defaultDate:date);if(date){date.setHours(0);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0)}return this._daylightSavingAdjust(date)},_daylightSavingAdjust:function(date){if(!date){return null}date.setHours(date.getHours()>12?date.getHours()+2:0);return date},_setDate:function(inst,date,endDate){var clear=!(date);var origMonth=inst.selectedMonth;var origYear=inst.selectedYear;date=this._determineDate(date,new Date());inst.selectedDay=inst.currentDay=date.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=date.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=date.getFullYear();if(origMonth!=inst.selectedMonth||origYear!=inst.selectedYear){this._notifyChange(inst)}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst))}},_getDate:function(inst){var startDate=(!inst.currentYear||(inst.input&&inst.input.val()=="")?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return startDate},_generateHTML:function(inst){var today=new Date();today=this._daylightSavingAdjust(new Date(today.getFullYear(),today.getMonth(),today.getDate()));var isRTL=this._get(inst,"isRTL");var showButtonPanel=this._get(inst,"showButtonPanel");var hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext");var navigationAsDateFormat=this._get(inst,"navigationAsDateFormat");var numMonths=this._getNumberOfMonths(inst);var showCurrentAtPos=this._get(inst,"showCurrentAtPos");var stepMonths=this._get(inst,"stepMonths");var stepBigMonths=this._get(inst,"stepBigMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var currentDate=this._daylightSavingAdjust((!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");var drawMonth=inst.drawMonth-showCurrentAtPos;var drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--}if(maxDate){var maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-numMonths[1]+1,maxDate.getDate()));maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;var prevText=this._get(inst,"prevText");prevText=(!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst)));var prev=(this._canAdjustMonth(inst,-1,drawYear,drawMonth)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#'+inst.id+"', -"+stepMonths+", 'M');\" title=\""+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>"));var nextText=this._get(inst,"nextText");nextText=(!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst)));var next=(this._canAdjustMonth(inst,+1,drawYear,drawMonth)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#'+inst.id+"', +"+stepMonths+", 'M');\" title=\""+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>"));var currentText=this._get(inst,"currentText");var gotoDate=(this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today);currentText=(!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst)));var controls=(!inst.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">'+this._get(inst,"closeText")+"</button>":"");var buttonPanel=(showButtonPanel)?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(isRTL?controls:"")+(this._isInRange(inst,gotoDate)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#'+inst.id+"');\">"+currentText+"</button>":"")+(isRTL?"":controls)+"</div>":"";var firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=(isNaN(firstDay)?0:firstDay);var dayNames=this._get(inst,"dayNames");var dayNamesShort=this._get(inst,"dayNamesShort");var dayNamesMin=this._get(inst,"dayNamesMin");var monthNames=this._get(inst,"monthNames");var monthNamesShort=this._get(inst,"monthNamesShort");var beforeShowDay=this._get(inst,"beforeShowDay");var showOtherMonths=this._get(inst,"showOtherMonths");var calculateWeek=this._get(inst,"calculateWeek")||this.iso8601Week;var endDate=inst.endDay?this._daylightSavingAdjust(new Date(inst.endYear,inst.endMonth,inst.endDay)):currentDate;var defaultDate=this._getDefaultDate(inst);var html="";for(var row=0;row<numMonths[0];row++){var group="";for(var col=0;col<numMonths[1];col++){var selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));var cornerClass=" ui-corner-all";var calender="";if(isMultiMonth){calender+='<div class="ui-datepicker-group ui-datepicker-group-';switch(col){case 0:calender+="first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+="last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+="middle";cornerClass="";break}calender+='">'}calender+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+cornerClass+'">'+(/all|left/.test(cornerClass)&&row==0?(isRTL?next:prev):"")+(/all|right/.test(cornerClass)&&row==0?(isRTL?prev:next):"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,selectedDate,row>0||col>0,monthNames,monthNamesShort)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var thead="";for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;thead+="<th"+((dow+firstDay+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+dayNames[day]+'">'+dayNamesMin[day]+"</span></th>"}calender+=thead+"</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==inst.selectedYear&&drawMonth==inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var numRows=(isMultiMonth?6:Math.ceil((leadDays+daysInMonth)/7));var printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(var dRow=0;dRow<numRows;dRow++){calender+="<tr>";var tbody="";for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((inst.input?inst.input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=otherMonth||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);tbody+='<td class="'+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(otherMonth?" ui-datepicker-other-month":"")+((printDate.getTime()==selectedDate.getTime()&&drawMonth==inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()==printDate.getTime()&&defaultDate.getTime()==selectedDate.getTime())?" "+this._dayOverClass:"")+(unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" "+this._currentClass:"")+(printDate.getTime()==today.getTime()?" ui-datepicker-today":""))+'"'+((!otherMonth||showOtherMonths)&&daySettings[2]?' title="'+daySettings[2]+'"':"")+(unselectable?"":" onclick=\"DP_jQuery.datepicker._selectDay('#"+inst.id+"',"+drawMonth+","+drawYear+', this);return false;"')+">"+(otherMonth?(showOtherMonths?printDate.getDate():"&#xa0;"):(unselectable?'<span class="ui-state-default">'+printDate.getDate()+"</span>":'<a class="ui-state-default'+(printDate.getTime()==today.getTime()?" ui-state-highlight":"")+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" ui-state-active":"")+'" href="#">'+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate)}calender+=tbody+"</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}calender+="</tbody></table>"+(isMultiMonth?"</div>"+((numMonths[0]>0&&col==numMonths[1]-1)?'<div class="ui-datepicker-row-break"></div>':""):"");group+=calender}html+=group}html+=buttonPanel+($.browser.msie&&parseInt($.browser.version,10)<7&&!inst.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");inst._keyEvent=false;return html},_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,selectedDate,secondary,monthNames,monthNamesShort){minDate=(inst.rangeStart&&minDate&&selectedDate<minDate?selectedDate:minDate);var changeMonth=this._get(inst,"changeMonth");var changeYear=this._get(inst,"changeYear");var showMonthAfterYear=this._get(inst,"showMonthAfterYear");var html='<div class="ui-datepicker-title">';var monthHtml="";if(secondary||!changeMonth){monthHtml+='<span class="ui-datepicker-month">'+monthNames[drawMonth]+"</span> "}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);monthHtml+='<select class="ui-datepicker-month" onchange="DP_jQuery.datepicker._selectMonthYear(\'#'+inst.id+"', this, 'M');\" onclick=\"DP_jQuery.datepicker._clickMonthYear('#"+inst.id+"');\">";for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNamesShort[month]+"</option>"}}monthHtml+="</select>"}if(!showMonthAfterYear){html+=monthHtml+((secondary||changeMonth||changeYear)&&(!(changeMonth&&changeYear))?"&#xa0;":"")}if(secondary||!changeYear){html+='<span class="ui-datepicker-year">'+drawYear+"</span>"}else{var years=this._get(inst,"yearRange").split(":");var year=0;var endYear=0;if(years.length!=2){year=drawYear-10;endYear=drawYear+10}else{if(years[0].charAt(0)=="+"||years[0].charAt(0)=="-"){year=drawYear+parseInt(years[0],10);endYear=drawYear+parseInt(years[1],10)}else{year=parseInt(years[0],10);endYear=parseInt(years[1],10)}}year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);html+='<select class="ui-datepicker-year" onchange="DP_jQuery.datepicker._selectMonthYear(\'#'+inst.id+"', this, 'Y');\" onclick=\"DP_jQuery.datepicker._clickMonthYear('#"+inst.id+"');\">";for(;year<=endYear;year++){html+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}html+="</select>"}if(showMonthAfterYear){html+=(secondary||changeMonth||changeYear?"&#xa0;":"")+monthHtml}html+="</div>";return html},_adjustInstDate:function(inst,offset,period){var year=inst.drawYear+(period=="Y"?offset:0);var month=inst.drawMonth+(period=="M"?offset:0);var day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=this._daylightSavingAdjust(new Date(year,month,day));var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period=="M"||period=="Y"){this._notifyChange(inst)}},_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply((inst.input?inst.input[0]:null),[inst.selectedYear,inst.selectedMonth+1,inst])}},_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(inst,minMax,checkRange){var date=this._determineDate(this._get(inst,minMax+"Date"),null);return(!checkRange||!inst.rangeStart?date:(!date||inst.rangeStart>date?inst.rangeStart:date))},_getDaysInMonth:function(year,month){return 32-new Date(year,month,32).getDate()},_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay()},_canAdjustMonth:function(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst);var date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(inst,date)},_isInRange:function(inst,date){var newMinDate=(!inst.rangeStart?null:this._daylightSavingAdjust(new Date(inst.selectedYear,inst.selectedMonth,inst.selectedDay)));newMinDate=(newMinDate&&inst.rangeStart<newMinDate?inst.rangeStart:newMinDate);var minDate=newMinDate||this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");return((!minDate||date>=minDate)&&(!maxDate||date<=maxDate))},_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")}},_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear}var date=(day?(typeof day=="object"?day:this._daylightSavingAdjust(new Date(year,month,day))):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst))}});function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null||props[name]==undefined){target[name]=props[name]}}return target}function isArray(a){return(a&&(($.browser.safari&&typeof a=="object"&&a.length)||(a.constructor&&a.constructor.toString().match(/\Array\(\)/))))}$.fn.datepicker=function(options){if(!$.datepicker.initialized){$(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv);$.datepicker.initialized=true}var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options=="string"&&(options=="isDisabled"||options=="getDate")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}if(options=="option"&&arguments.length==2&&typeof arguments[1]=="string"){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}return this.each(function(){typeof options=="string"?$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs)):$.datepicker._attachDatepicker(this,options)})};$.datepicker=new Datepicker();$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.7.2";window.DP_jQuery=$})(jQuery);;
/*
 * jQuery UI Tabs 1.7.3
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function(c){var b=0,a=0;c.widget("ui.tabs",{_init:function(){if(this.options.deselectable!==undefined){this.options.collapsible=this.options.deselectable}this._tabify(true)},_setData:function(d,e){if(d=="selected"){if(this.options.collapsible&&e==this.options.selected){return}this.select(e)}else{this.options[d]=e;if(d=="deselectable"){this.options.collapsible=e}this._tabify()}},_tabId:function(d){return d.title&&d.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+(++b)},_sanitizeSelector:function(d){return d.replace(/:/g,"\\:")},_cookie:function(){var d=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+(++a));return c.cookie.apply(null,[d].concat(c.makeArray(arguments)))},_ui:function(e,d){return{tab:e,panel:d,index:this.anchors.index(e)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var d=c(this);d.html(d.data("label.tabs")).removeData("label.tabs")})},_tabify:function(q){this.list=this.element.children("ul:first");this.lis=c("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return c("a",this)[0]});this.panels=c([]);var r=this,f=this.options;var e=/^#.+/;this.anchors.each(function(u,o){var s=c(o).attr("href");var v=s.split("#")[0],w;if(v&&(v===location.toString().split("#")[0]||(w=c("base")[0])&&v===w.href)){s=o.hash;o.href=s}if(e.test(s)){r.panels=r.panels.add(r._sanitizeSelector(s))}else{if(s!="#"){c.data(o,"href.tabs",s);c.data(o,"load.tabs",s.replace(/#.*$/,""));var y=r._tabId(o);o.href="#"+y;var x=c("#"+y);if(!x.length){x=c(f.panelTemplate).attr("id",y).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(r.panels[u-1]||r.list);x.data("destroy.tabs",true)}r.panels=r.panels.add(x)}else{f.disabled.push(u)}}});if(q){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(f.selected===undefined){if(location.hash){this.anchors.each(function(s,o){if(o.hash==location.hash){f.selected=s;return false}})}if(typeof f.selected!="number"&&f.cookie){f.selected=parseInt(r._cookie(),10)}if(typeof f.selected!="number"&&this.lis.filter(".ui-tabs-selected").length){f.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}f.selected=f.selected||0}else{if(f.selected===null){f.selected=-1}}f.selected=((f.selected>=0&&this.anchors[f.selected])||f.selected<0)?f.selected:0;f.disabled=c.unique(f.disabled.concat(c.map(this.lis.filter(".ui-state-disabled"),function(s,o){return r.lis.index(s)}))).sort();if(c.inArray(f.selected,f.disabled)!=-1){f.disabled.splice(c.inArray(f.selected,f.disabled),1)}this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(f.selected>=0&&this.anchors.length){this.panels.eq(f.selected).removeClass("ui-tabs-hide");this.lis.eq(f.selected).addClass("ui-tabs-selected ui-state-active");r.element.queue("tabs",function(){r._trigger("show",null,r._ui(r.anchors[f.selected],r.panels[f.selected]))});this.load(f.selected)}c(window).bind("unload",function(){r.lis.add(r.anchors).unbind(".tabs");r.lis=r.anchors=r.panels=null})}else{f.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}this.element[f.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");if(f.cookie){this._cookie(f.selected,f.cookie)}for(var j=0,p;(p=this.lis[j]);j++){c(p)[c.inArray(j,f.disabled)!=-1&&!c(p).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled")}if(f.cache===false){this.anchors.removeData("cache.tabs")}this.lis.add(this.anchors).unbind(".tabs");if(f.event!="mouseover"){var h=function(o,i){if(i.is(":not(.ui-state-disabled)")){i.addClass("ui-state-"+o)}};var l=function(o,i){i.removeClass("ui-state-"+o)};this.lis.bind("mouseover.tabs",function(){h("hover",c(this))});this.lis.bind("mouseout.tabs",function(){l("hover",c(this))});this.anchors.bind("focus.tabs",function(){h("focus",c(this).closest("li"))});this.anchors.bind("blur.tabs",function(){l("focus",c(this).closest("li"))})}var d,k;if(f.fx){if(c.isArray(f.fx)){d=f.fx[0];k=f.fx[1]}else{d=k=f.fx}}function g(i,o){i.css({display:""});if(c.browser.msie&&o.opacity){i[0].style.removeAttribute("filter")}}var m=k?function(i,o){c(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.hide().removeClass("ui-tabs-hide").animate(k,k.duration||"normal",function(){g(o,k);r._trigger("show",null,r._ui(i,o[0]))})}:function(i,o){c(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");r._trigger("show",null,r._ui(i,o[0]))};var n=d?function(o,i){i.animate(d,d.duration||"normal",function(){r.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");g(i,d);r.element.dequeue("tabs")})}:function(o,i,s){r.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");r.element.dequeue("tabs")};this.anchors.bind(f.event+".tabs",function(){var o=this,u=c(this).closest("li"),i=r.panels.filter(":not(.ui-tabs-hide)"),s=c(r._sanitizeSelector(this.hash));if((u.hasClass("ui-tabs-selected")&&!f.collapsible)||u.hasClass("ui-state-disabled")||u.hasClass("ui-state-processing")||r._trigger("select",null,r._ui(this,s[0]))===false){this.blur();return false}f.selected=r.anchors.index(this);r.abort();if(f.collapsible){if(u.hasClass("ui-tabs-selected")){f.selected=-1;if(f.cookie){r._cookie(f.selected,f.cookie)}r.element.queue("tabs",function(){n(o,i)}).dequeue("tabs");this.blur();return false}else{if(!i.length){if(f.cookie){r._cookie(f.selected,f.cookie)}r.element.queue("tabs",function(){m(o,s)});r.load(r.anchors.index(this));this.blur();return false}}}if(f.cookie){r._cookie(f.selected,f.cookie)}if(s.length){if(i.length){r.element.queue("tabs",function(){n(o,i)})}r.element.queue("tabs",function(){m(o,s)});r.load(r.anchors.index(this))}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(c.browser.msie){this.blur()}});this.anchors.bind("click.tabs",function(){return false})},destroy:function(){var d=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=c.data(this,"href.tabs");if(e){this.href=e}var f=c(this).unbind(".tabs");c.each(["href","load","cache"],function(g,h){f.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){if(c.data(this,"destroy.tabs")){c(this).remove()}else{c(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}});if(d.cookie){this._cookie(null,d.cookie)}},add:function(g,f,e){if(e===undefined){e=this.anchors.length}var d=this,i=this.options,k=c(i.tabTemplate.replace(/#\{href\}/g,g).replace(/#\{label\}/g,f)),j=!g.indexOf("#")?g.replace("#",""):this._tabId(c("a",k)[0]);k.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var h=c("#"+j);if(!h.length){h=c(i.panelTemplate).attr("id",j).data("destroy.tabs",true)}h.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(e>=this.lis.length){k.appendTo(this.list);h.appendTo(this.list[0].parentNode)}else{k.insertBefore(this.lis[e]);h.insertBefore(this.panels[e])}i.disabled=c.map(i.disabled,function(m,l){return m>=e?++m:m});this._tabify();if(this.anchors.length==1){k.addClass("ui-tabs-selected ui-state-active");h.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){d._trigger("show",null,d._ui(d.anchors[0],d.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[e],this.panels[e]))},remove:function(d){var f=this.options,g=this.lis.eq(d).remove(),e=this.panels.eq(d).remove();if(g.hasClass("ui-tabs-selected")&&this.anchors.length>1){this.select(d+(d+1<this.anchors.length?1:-1))}f.disabled=c.map(c.grep(f.disabled,function(j,h){return j!=d}),function(j,h){return j>=d?--j:j});this._tabify();this._trigger("remove",null,this._ui(g.find("a")[0],e[0]))},enable:function(d){var e=this.options;if(c.inArray(d,e.disabled)==-1){return}this.lis.eq(d).removeClass("ui-state-disabled");e.disabled=c.grep(e.disabled,function(g,f){return g!=d});this._trigger("enable",null,this._ui(this.anchors[d],this.panels[d]))},disable:function(e){var d=this,f=this.options;if(e!=f.selected){this.lis.eq(e).addClass("ui-state-disabled");f.disabled.push(e);f.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[e],this.panels[e]))}},select:function(d){if(typeof d=="string"){d=this.anchors.index(this.anchors.filter("[href$="+d+"]"))}else{if(d===null){d=-1}}if(d==-1&&this.options.collapsible){d=this.options.selected}this.anchors.eq(d).trigger(this.options.event+".tabs")},load:function(g){var e=this,i=this.options,d=this.anchors.eq(g)[0],f=c.data(d,"load.tabs");this.abort();if(!f||this.element.queue("tabs").length!==0&&c.data(d,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(g).addClass("ui-state-processing");if(i.spinner){var h=c("span",d);h.data("label.tabs",h.html()).html(i.spinner)}this.xhr=c.ajax(c.extend({},i.ajaxOptions,{url:f,success:function(k,j){c(e._sanitizeSelector(d.hash)).html(k);e._cleanup();if(i.cache){c.data(d,"cache.tabs",true)}e._trigger("load",null,e._ui(e.anchors[g],e.panels[g]));try{i.ajaxOptions.success(k,j)}catch(l){}e.element.dequeue("tabs")}}))},abort:function(){this.element.queue([]);this.panels.stop(false,true);if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup()},url:function(e,d){this.anchors.eq(e).removeData("cache.tabs").data("load.tabs",d)},length:function(){return this.anchors.length}});c.extend(c.ui.tabs,{version:"1.7.3",getter:"length",defaults:{ajaxOptions:null,cache:false,cookie:null,collapsible:false,disabled:[],event:"click",fx:null,idPrefix:"ui-tabs-",panelTemplate:"<div></div>",spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'}});c.extend(c.ui.tabs.prototype,{rotation:null,rotate:function(f,h){var d=this,i=this.options;var e=d._rotate||(d._rotate=function(j){clearTimeout(d.rotation);d.rotation=setTimeout(function(){var k=i.selected;d.select(++k<d.anchors.length?k:0)},f);if(j){j.stopPropagation()}});var g=d._unrotate||(d._unrotate=!h?function(j){if(j.clientX){d.rotate(null)}}:function(j){t=i.selected;e()});if(f){this.element.bind("tabsshow",e);this.anchors.bind(i.event+".tabs",g);e()}else{clearTimeout(d.rotation);this.element.unbind("tabsshow",e);this.anchors.unbind(i.event+".tabs",g);delete this._rotate;delete this._unrotate}}})})(jQuery);

/*>>>>>>>>>> jquery-custom-base.js <<<<<<<<<<*/
function listOddEven() {
	if(j$('.alternateRows').length > 0)
//		j$('form.alternateRows fieldset:odd').addClass('odd');
//		j$('form.alternateRows fieldset:even').addClass('even');
		j$('table.alternateRows tr:odd').addClass('odd');
		j$('table.alternateRows tr:even').addClass('even');
		j$('div.alternateRows div.searchResultsContentBlock:odd').addClass('odd');
		j$('div.alternateRows div.searchResultsContentBlock:even').addClass('even');
}


j$(document).ready(function() {
	
	listOddEven();
	
	j$('#lev1opt8 ul').remove();//CG-1022
	
	// Clears input fields when focused and fills back when unfocused.
	// To enable this functionality on any input text box, add the class "default-value" to the input field.
	
	j$('.default-value').each(function() {
	    var default_value = this.value;   
	    j$(this).focus(function() {
	        if(this.value == default_value) {
	            this.value = '';           
	        }
	    });
	    j$(this).blur(function() {
	        if(this.value == '') {           
	            this.value = default_value;
	        }
	    });
	});
	
	
	// Quickview button show/hide
	
	 j$('.product-image').mouseenter(function(z) {
		 j$(this).find('div.quickViewButton').fadeIn();
		 j$(this).addClass('product-image-hover');
	 });	
	 
	 j$('.product-image').mouseleave(function(z) {
		 j$(this).find('div.quickViewButton').fadeOut();
		 j$(this).removeClass('product-image-hover');
	 });	 
	 
	 
	
	// jQuery UI Tabs component
	// The container needs to have asigned class="tabs"
	// Documentation on how to implement: http://jqueryui.com/demos/tabs/
	j$(".tabs").tabs();

	// Show/Hide "Forgot Password" block
	// the trigger needs to have .forgot-password class
	// the block needs to have .retrieve-password class 
	j$(".forgot-password").click(function () {
		j$(".retrieve-password").toggle();
		});
		
		
	// jQuery Zoom for product details page
	
	var zoomoptions = {
	    zoomWidth: 500,
	    zoomHeight: 350,
        xOffset: 10,
        yOffset: -1,
        title: false,
        hideEffect: "fadeout",
        showPreload: true,
        position: "right" 
	};
	
	j$('#zoomLarge').jqzoom(zoomoptions);	 	
	
	
});






/*>>>>>>>>>> jquery-custom-cyclegear.js <<<<<<<<<<*/

/*>>>>>>>>>> jquery.tablednd.js <<<<<<<<<<*/
/**
 * TableDnD plug-in for JQuery, allows you to drag and drop table rows
 * You can set up various options to control how the system will work
 * Copyright (c) Denis Howlett <denish@isocra.com>
 * Licensed like jQuery, see http://docs.jquery.com/License.
 *
 * Configuration options:
 * 
 * onDragStyle
 *     This is the style that is assigned to the row during drag. There are limitations to the styles that can be
 *     associated with a row (such as you can't assign a border--well you can, but it won't be
 *     displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
 *     a map (as used in the jQuery css(...) function).
 * onDropStyle
 *     This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
 *     to what you can do. Also this replaces the original style, so again consider using onDragClass which
 *     is simply added and then removed on drop.
 * onDragClass
 *     This class is added for the duration of the drag and then removed when the row is dropped. It is more
 *     flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
 *     is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
 *     stylesheet.
 * onDrop
 *     Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
 *     and the row that was dropped. You can work out the new order of the rows by using
 *     table.rows.
 * onDragStart
 *     Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
 *     table and the row which the user has started to drag.
 * onAllowDrop
 *     Pass a function that will be called as a row is over another row. If the function returns true, allow 
 *     dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
 *     the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
 * scrollAmount
 *     This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
 *     window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
 *     FF3 beta
 * dragHandle
 *     This is the name of a class that you assign to one or more cells in each row that is draggable. If you
 *     specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
 *     will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
 *     the whole row is draggable.
 * 
 * Other ways to control behaviour:
 *
 * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
 * that you don't want to be draggable.
 *
 * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
 * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
 * an ID as must all the rows.
 *
 * Other methods:
 *
 * $("...").tableDnDUpdate() 
 * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
 * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
 * The table maintains the original configuration (so you don't have to specify it again).
 *
 * $("...").tableDnDSerialize()
 * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
 * called from anywhere and isn't dependent on the currentTable being set up correctly before calling
 *
 * Known problems:
 * - Auto-scoll has some problems with IE7  (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
 * 
 * Version 0.2: 2008-02-20 First public version
 * Version 0.3: 2008-02-07 Added onDragStart option
 *                         Made the scroll amount configurable (default is 5 as before)
 * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
 *                         Added onAllowDrop to control dropping
 *                         Fixed a bug which meant that you couldn't set the scroll amount in both directions
 *                         Added serialize method
 * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
 *                         draggable
 *                         Improved the serialize method to use a default (and settable) regular expression.
 *                         Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
 */
jQuery.tableDnD = {
    /** Keep hold of the current table being dragged */
    currentTable : null,
    /** Keep hold of the current drag object if any */
    dragObject: null,
    /** The current mouse offset */
    mouseOffset: null,
    /** Remember the old value of Y so that we don't do too much processing */
    oldY: 0,

    /** Actually build the structure */
    build: function(options) {
        // Set up the defaults if any

        this.each(function() {
            // This is bound to each matching table, set up the defaults and override with user options
            this.tableDnDConfig = jQuery.extend({
                onDragStyle: null,
                onDropStyle: null,
				// Add in the default class for whileDragging
				onDragClass: "tDnD_whileDrag",
                onDrop: null,
                onDragStart: null,
                scrollAmount: 5,
				serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
				serializeParamName: null, // If you want to specify another parameter name instead of the table ID
                dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
            }, options || {});
            // Now make the rows draggable
            jQuery.tableDnD.makeDraggable(this);
        });

        // Now we need to capture the mouse up and mouse move event
        // We can use bind so that we don't interfere with other event handlers
        jQuery(document)
            .bind('mousemove', jQuery.tableDnD.mousemove)
            .bind('mouseup', jQuery.tableDnD.mouseup);

        // Don't break the chain
        return this;
    },

    /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
    makeDraggable: function(table) {
        var config = table.tableDnDConfig;
		if (table.tableDnDConfig.dragHandle) {
			// We only need to add the event to the specified cells
			var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
			cells.each(function() {
				// The cell is bound to "this"
                jQuery(this).mousedown(function(ev) {
                    jQuery.tableDnD.dragObject = this.parentNode;
                    jQuery.tableDnD.currentTable = table;
                    jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
                    if (config.onDragStart) {
                        // Call the onDrop method if there is one
                        config.onDragStart(table, this);
                    }
                    return false;
                });
			})
		} else {
			// For backwards compatibility, we add the event to the whole row
	        var rows = jQuery("tr", table); // get all the rows as a wrapped set
	        rows.each(function() {
				// Iterate through each row, the row is bound to "this"
				var row = jQuery(this);
				if (! row.hasClass("nodrag")) {
	                row.mousedown(function(ev) {
	                    if (ev.target.tagName == "TD") {
	                        jQuery.tableDnD.dragObject = this;
	                        jQuery.tableDnD.currentTable = table;
	                        jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
	                        if (config.onDragStart) {
	                            // Call the onDrop method if there is one
	                            config.onDragStart(table, this);
	                        }
	                        return false;
	                    }
	                })//.css("cursor", "pointer"); // Store the tableDnD object
				}
			});
		}
	},

	updateTables: function() {
		this.each(function() {
			// this is now bound to each matching table
			if (this.tableDnDConfig) {
				jQuery.tableDnD.makeDraggable(this);
			}
		})
	},

    /** Get the mouse coordinates from the event (allowing for browser differences) */
    mouseCoords: function(ev){
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    },

    /** Given a target element and a mouse event, get the mouse offset from that element.
        To do this we need the element's position and the mouse position */
    getMouseOffset: function(target, ev) {
        ev = ev || window.event;

        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    },

    /** Get the position of an element by going up the DOM tree and adding up all the offsets */
    getPosition: function(e){
        var left = 0;
        var top  = 0;
        /** Safari fix -- thanks to Luis Chato for this! */
        if (e.offsetHeight == 0) {
            /** Safari 2 doesn't correctly grab the offsetTop of a table row
            this is detailed here:
            http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
            the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
            note that firefox will return a text node as a first child, so designing a more thorough
            solution may need to take that into account, for now this seems to work in firefox, safari, ie */
            e = e.firstChild; // a table cell
        }

		if(e != null){
	        while (e.offsetParent){
	            left += e.offsetLeft;
	            top  += e.offsetTop;
	            e     = e.offsetParent;
	        }
	
	        left += e.offsetLeft;
	        top  += e.offsetTop;
		}
        return {x:left, y:top};
    },

    mousemove: function(ev) {
        if (jQuery.tableDnD.dragObject == null) {
            return;
        }

        var dragObj = jQuery(jQuery.tableDnD.dragObject);
        var config = jQuery.tableDnD.currentTable.tableDnDConfig;
        var mousePos = jQuery.tableDnD.mouseCoords(ev);
        var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
        //auto scroll the window
	    var yOffset = window.pageYOffset;
	 	if (document.all) {
	        // Windows version
	        //yOffset=document.body.scrollTop;
	        if (typeof document.compatMode != 'undefined' &&
	             document.compatMode != 'BackCompat') {
	           yOffset = document.documentElement.scrollTop;
	        }
	        else if (typeof document.body != 'undefined') {
	           yOffset=document.body.scrollTop;
	        }

	    }
		    
		if (mousePos.y-yOffset < config.scrollAmount) {
	    	window.scrollBy(0, -config.scrollAmount);
	    } else {
            var windowHeight = window.innerHeight ? window.innerHeight
                    : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
            if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
                window.scrollBy(0, config.scrollAmount);
            }
        }


        if (y != jQuery.tableDnD.oldY) {
            // work out if we're going up or down...
            var movingDown = y > jQuery.tableDnD.oldY;
            // update the old value
            jQuery.tableDnD.oldY = y;
            // update the style to show we're dragging
			if (config.onDragClass) {
				dragObj.addClass(config.onDragClass);
			} else {
	            dragObj.css(config.onDragStyle);
			}
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
            if (currentRow) {
                // TODO worry about what happens when there are multiple TBODIES
                if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
                } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
                }
            }
        }

        return false;
    },

    /** We're only worried about the y position really, because we can only move rows up and down */
    findDropTargetRow: function(draggedRow, y) {
        var rows = jQuery.tableDnD.currentTable.rows;
        for (var i=0; i<rows.length; i++) {
            var row = rows[i];
            var rowY    = this.getPosition(row).y;
            var rowHeight = parseInt(row.offsetHeight)/2;
            if (row.offsetHeight == 0) {
                rowY = this.getPosition(row.firstChild).y;
                rowHeight = parseInt(row.firstChild.offsetHeight)/2;
            }
            // Because we always have to insert before, we need to offset the height a bit
            if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                // that's the row we're over
				// If it's the same as the current row, ignore it
				if (row == draggedRow) {return null;}
                var config = jQuery.tableDnD.currentTable.tableDnDConfig;
                if (config.onAllowDrop) {
                    if (config.onAllowDrop(draggedRow, row)) {
                        return row;
                    } else {
                        return null;
                    }
                } else {
					// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
                    var nodrop = jQuery(row).hasClass("nodrop");
                    if (! nodrop) {
                        return row;
                    } else {
                        return null;
                    }
                }
                return row;
            }
        }
        return null;
    },

    mouseup: function(e) {
        if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
            var droppedRow = jQuery.tableDnD.dragObject;
            var config = jQuery.tableDnD.currentTable.tableDnDConfig;
            // If we have a dragObject, then we need to release it,
            // The row will already have been moved to the right place so we just reset stuff
			if (config.onDragClass) {
	            jQuery(droppedRow).removeClass(config.onDragClass);
			} else {
	            jQuery(droppedRow).css(config.onDropStyle);
			}
            jQuery.tableDnD.dragObject   = null;
            if (config.onDrop) {
                // Call the onDrop method if there is one
                config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
            }
            jQuery.tableDnD.currentTable = null; // let go of the table too
        }
    },

    serialize: function() {
        if (jQuery.tableDnD.currentTable) {
            return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
        } else {
            return "Error: No Table id set, you need to set an id on your table and every row";
        }
    },

	serializeTable: function(table) {
        var result = "";
        var tableId = table.id;
        var rows = table.rows;
        for (var i=0; i<rows.length; i++) {
            if (result.length > 0) result += "&";
            var rowId = rows[i].id;
            if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
                rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
            }

            result += tableId + '[]=' + rowId;
        }
        return result;
	},

	serializeTables: function() {
        var result = "";
        this.each(function() {
			// this is now bound to each matching table
			result += jQuery.tableDnD.serializeTable(this);
		});
        return result;
    }

}

jQuery.fn.extend(
	{
		tableDnD : jQuery.tableDnD.build,
		tableDnDUpdate : jQuery.tableDnD.updateTables,
		tableDnDSerialize: jQuery.tableDnD.serializeTables
	}
);

/*>>>>>>>>>> jquery.bgiframe.min.js <<<<<<<<<<*/
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 19:45:56 -0400 (Sat, 21 Jul 2007) $
 * $Rev: 2447 $
 *
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);

/*>>>>>>>>>> jquery.hoverIntent.js <<<<<<<<<<*/
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
*	interval: 50,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 100,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @return    The object (aka "this") that called hoverIntent, and the event object
* @author    Brian Cherne <brian@cherne.net>
* 
* modified by Karl Swedberg. Namespaced events in order to work better with clueTip plugin
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode}catch(e){p=this}}if(p==this){return false}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove.cluetip",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove.cluetip",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseover.cluetip',handleHover).bind('mouseout.cluetip',handleHover)}})(jQuery);

/*>>>>>>>>>> jquery.cluetip.js <<<<<<<<<<*/
/*
 * jQuery clueTip plugin
 * Version 1.0.4  (June 28, 2009)
 * @requires jQuery v1.2.6+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Full list of options/settings can be found at the bottom of this file and at http://plugins.learningjquery.com/cluetip/
 *
 * Examples can be found at http://plugins.learningjquery.com/cluetip/demo/
 *
*/
;(function($){$.cluetip={version:'1.0.4'};var $cluetip,$cluetipInner,$cluetipOuter,$cluetipTitle,$cluetipArrows,$cluetipWait,$dropShadow,imgCount;$.fn.cluetip=function(js,options){if(typeof js=='object'){options=js;js=null}if(js=='destroy'){return this.unbind('.cluetip')}return this.each(function(index){var link=this,$this=$(this);var opts=$.extend(true,{},$.fn.cluetip.defaults,options||{},$.metadata?$this.metadata():$.meta?$this.data():{});var cluetipContents=false;var cluezIndex=+opts.cluezIndex;$this.data('thisInfo',{title:link.title,zIndex:cluezIndex});var isActive=false,closeOnDelay=0;if(!$('#cluetip').length){$(['<div id="cluetip">','<div id="cluetip-outer">','<h3 id="cluetip-title"></h3>','<div id="cluetip-inner"></div>','</div>','<div id="cluetip-extra"></div>','<div id="cluetip-arrows" class="cluetip-arrows"></div>','</div>'].join(''))[insertionType](insertionElement).hide();$cluetip=$('#cluetip').css({position:'absolute'});$cluetipOuter=$('#cluetip-outer').css({position:'relative',zIndex:cluezIndex});$cluetipInner=$('#cluetip-inner');$cluetipTitle=$('#cluetip-title');$cluetipArrows=$('#cluetip-arrows');$cluetipWait=$('<div id="cluetip-waitimage"></div>').css({position:'absolute'}).insertBefore($cluetip).hide()}var dropShadowSteps=(opts.dropShadow)?+opts.dropShadowSteps:0;if(!$dropShadow){$dropShadow=$([]);for(var i=0;i<dropShadowSteps;i++){$dropShadow=$dropShadow.add($('<div></div>').css({zIndex:cluezIndex-1,opacity:.1,top:1+i,left:1+i}))};$dropShadow.css({position:'absolute',backgroundColor:'#000'}).prependTo($cluetip)}var tipAttribute=$this.attr(opts.attribute),ctClass=opts.cluetipClass;if(!tipAttribute&&!opts.splitTitle&&!js)return true;if(opts.local&&opts.localPrefix){tipAttribute=opts.localPrefix+tipAttribute}if(opts.local&&opts.hideLocal){$(tipAttribute+':first').hide()}var tOffset=parseInt(opts.topOffset,10),lOffset=parseInt(opts.leftOffset,10);var tipHeight,wHeight,defHeight=isNaN(parseInt(opts.height,10))?'auto':(/\D/g).test(opts.height)?opts.height:opts.height+'px';var sTop,linkTop,posY,tipY,mouseY,baseline;var tipInnerWidth=parseInt(opts.width,10)||275,tipWidth=tipInnerWidth+(parseInt($cluetip.css('paddingLeft'),10)||0)+(parseInt($cluetip.css('paddingRight'),10)||0)+dropShadowSteps,linkWidth=this.offsetWidth,linkLeft,posX,tipX,mouseX,winWidth;var tipParts;var tipTitle=(opts.attribute!='title')?$this.attr(opts.titleAttribute):'';if(opts.splitTitle){if(tipTitle==undefined){tipTitle=''}tipParts=tipTitle.split(opts.splitTitle);tipTitle=tipParts.shift()}if(opts.escapeTitle){tipTitle=tipTitle.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;')}var localContent;function returnFalse(){return false}var activate=function(event){if(!opts.onActivate($this)){return false}isActive=true;$cluetip.removeClass().css({width:tipInnerWidth});if(tipAttribute==$this.attr('href')){$this.css('cursor',opts.cursor)}if(opts.hoverClass){$this.addClass(opts.hoverClass)}linkTop=posY=$this.offset().top;linkLeft=$this.offset().left;mouseX=event.pageX;mouseY=event.pageY;if(link.tagName.toLowerCase()!='area'){sTop=$(document).scrollTop();winWidth=$(window).width()}if(opts.positionBy=='fixed'){posX=linkWidth+linkLeft+lOffset;$cluetip.css({left:posX})}else{posX=(linkWidth>linkLeft&&linkLeft>tipWidth)||linkLeft+linkWidth+tipWidth+lOffset>winWidth?linkLeft-tipWidth-lOffset:linkWidth+linkLeft+lOffset;if(link.tagName.toLowerCase()=='area'||opts.positionBy=='mouse'||linkWidth+tipWidth>winWidth){if(mouseX+20+tipWidth>winWidth){$cluetip.addClass(' cluetip-'+ctClass);posX=(mouseX-tipWidth-lOffset)>=0?mouseX-tipWidth-lOffset-parseInt($cluetip.css('marginLeft'),10)+parseInt($cluetipInner.css('marginRight'),10):mouseX-(tipWidth/2)}else{posX=mouseX+lOffset}}var pY=posX<0?event.pageY+tOffset:event.pageY;$cluetip.css({left:(posX>0&&opts.positionBy!='bottomTop')?posX:(mouseX+(tipWidth/2)>winWidth)?winWidth/2-tipWidth/2:Math.max(mouseX-(tipWidth/2),0),zIndex:$this.data('thisInfo').zIndex});$cluetipArrows.css({zIndex:$this.data('thisInfo').zIndex+1})}wHeight=$(window).height();if(js){if(typeof js=='function'){js=js(link)}$cluetipInner.html(js);cluetipShow(pY)}else if(tipParts){var tpl=tipParts.length;$cluetipInner.html(tipParts[0]);if(tpl>1){for(var i=1;i<tpl;i++){$cluetipInner.append('<div class="split-body">'+tipParts[i]+'</div>')}}cluetipShow(pY)}else if(!opts.local&&tipAttribute.indexOf('#')!=0){if(/\.(jpe?g|tiff?|gif|png)$/i.test(tipAttribute)){$cluetipInner.html('<img src="'+tipAttribute+'" alt="'+tipTitle+'" />');cluetipShow(pY)}else if(cluetipContents&&opts.ajaxCache){$cluetipInner.html(cluetipContents);cluetipShow(pY)}else{var optionBeforeSend=opts.ajaxSettings.beforeSend,optionError=opts.ajaxSettings.error,optionSuccess=opts.ajaxSettings.success,optionComplete=opts.ajaxSettings.complete;var ajaxSettings={cache:false,url:tipAttribute,beforeSend:function(xhr){if(optionBeforeSend){optionBeforeSend.call(link,xhr,$cluetip,$cluetipInner)}$cluetipOuter.children().empty();if(opts.waitImage){$cluetipWait.css({top:mouseY+20,left:mouseX+20,zIndex:$this.data('thisInfo').zIndex-1}).show()}},error:function(xhr,textStatus){if(isActive){if(optionError){optionError.call(link,xhr,textStatus,$cluetip,$cluetipInner)}else{$cluetipInner.html('<i>sorry, the contents could not be loaded</i>')}}},success:function(data,textStatus){cluetipContents=opts.ajaxProcess.call(link,data);if(isActive){if(optionSuccess){optionSuccess.call(link,data,textStatus,$cluetip,$cluetipInner)}$cluetipInner.html(cluetipContents)}},complete:function(xhr,textStatus){if(optionComplete){optionComplete.call(link,xhr,textStatus,$cluetip,$cluetipInner)}imgCount=$('#cluetip-inner img').length;if(imgCount&&!$.browser.opera){$('#cluetip-inner img').bind('load error',function(){imgCount--;if(imgCount<1){$cluetipWait.hide();if(isActive)cluetipShow(pY)}})}else{$cluetipWait.hide();if(isActive){cluetipShow(pY)}}}};var ajaxMergedSettings=$.extend(true,{},opts.ajaxSettings,ajaxSettings);$.ajax(ajaxMergedSettings)}}else if(opts.local){var $localContent=$(tipAttribute+(/#\S+$/.test(tipAttribute)?'':':eq('+index+')')).clone(true).show();$cluetipInner.html($localContent);cluetipShow(pY)}};var cluetipShow=function(bpY){$cluetip.addClass('cluetip-'+ctClass);if(opts.truncate){var $truncloaded=$cluetipInner.text().slice(0,opts.truncate)+'...';$cluetipInner.html($truncloaded)}function doNothing(){};tipTitle?$cluetipTitle.show().html(tipTitle):(opts.showTitle)?$cluetipTitle.show().html('&nbsp;'):$cluetipTitle.hide();if(opts.sticky){var $closeLink=$('<div id="cluetip-close"><a href="#">'+opts.closeText+'</a></div>');(opts.closePosition=='bottom')?$closeLink.appendTo($cluetipInner):(opts.closePosition=='title')?$closeLink.prependTo($cluetipTitle):$closeLink.prependTo($cluetipInner);$closeLink.bind('click.cluetip',function(){cluetipClose();return false});if(opts.mouseOutClose){$cluetip.bind('mouseleave.cluetip',function(){cluetipClose()})}else{$cluetip.unbind('mouseleave.cluetip')}}var direction='';$cluetipOuter.css({zIndex:$this.data('thisInfo').zIndex,overflow:defHeight=='auto'?'visible':'auto',height:defHeight});tipHeight=defHeight=='auto'?Math.max($cluetip.outerHeight(),$cluetip.height()):parseInt(defHeight,10);tipY=posY;baseline=sTop+wHeight;if(opts.positionBy=='fixed'){tipY=posY-opts.dropShadowSteps+tOffset}else if((posX<mouseX&&Math.max(posX,0)+tipWidth>mouseX)||opts.positionBy=='bottomTop'){if(posY+tipHeight+tOffset>baseline&&mouseY-sTop>tipHeight+tOffset){tipY=mouseY-tipHeight-tOffset;direction='top'}else{tipY=mouseY+tOffset;direction='bottom'}}else if(posY+tipHeight+tOffset>baseline){tipY=(tipHeight>=wHeight)?sTop:baseline-tipHeight-tOffset}else if($this.css('display')=='block'||link.tagName.toLowerCase()=='area'||opts.positionBy=="mouse"){tipY=bpY-tOffset}else{tipY=posY-opts.dropShadowSteps}if(direction==''){posX<linkLeft?direction='left':direction='right'}$cluetip.css({top:tipY+'px'}).removeClass().addClass('clue-'+direction+'-'+ctClass).addClass(' cluetip-'+ctClass);if(opts.arrows){var bgY=(posY-tipY-opts.dropShadowSteps);$cluetipArrows.css({top:(/(left|right)/.test(direction)&&posX>=0&&bgY>0)?bgY+'px':/(left|right)/.test(direction)?0:''}).show()}else{$cluetipArrows.hide()}$dropShadow.hide();$cluetip.hide()[opts.fx.open](opts.fx.open!='show'&&opts.fx.openSpeed);if(opts.dropShadow){$dropShadow.css({height:tipHeight,width:tipInnerWidth,zIndex:$this.data('thisInfo').zIndex-1}).show()}if($.fn.bgiframe){$cluetip.bgiframe()}if(opts.delayedClose>0){closeOnDelay=setTimeout(cluetipClose,opts.delayedClose)}opts.onShow.call(link,$cluetip,$cluetipInner)};var inactivate=function(event){isActive=false;$cluetipWait.hide();if(!opts.sticky||(/click|toggle/).test(opts.activation)){cluetipClose();clearTimeout(closeOnDelay)};if(opts.hoverClass){$this.removeClass(opts.hoverClass)}};var cluetipClose=function(){$cluetipOuter.parent().hide().removeClass();opts.onHide.call(link,$cluetip,$cluetipInner);$this.removeClass('cluetip-clicked');if(tipTitle){$this.attr(opts.titleAttribute,tipTitle)}$this.css('cursor','');if(opts.arrows)$cluetipArrows.css({top:''})};$(document).bind('hideCluetip',function(e){cluetipClose()});if((/click|toggle/).test(opts.activation)){$this.bind('click.cluetip',function(event){if($cluetip.is(':hidden')||!$this.is('.cluetip-clicked')){activate(event);$('.cluetip-clicked').removeClass('cluetip-clicked');$this.addClass('cluetip-clicked')}else{inactivate(event)}this.blur();return false})}else if(opts.activation=='focus'){$this.bind('focus.cluetip',function(event){activate(event)});$this.bind('blur.cluetip',function(event){inactivate(event)})}else{$this[opts.clickThrough?'unbind':'bind']('click',returnFalse);var mouseTracks=function(evt){if(opts.tracking==true){var trackX=posX-evt.pageX;var trackY=tipY?tipY-evt.pageY:posY-evt.pageY;$this.bind('mousemove.cluetip',function(evt){$cluetip.css({left:evt.pageX+trackX,top:evt.pageY+trackY})})}};if($.fn.hoverIntent&&opts.hoverIntent){$this.hoverIntent({sensitivity:opts.hoverIntent.sensitivity,interval:opts.hoverIntent.interval,over:function(event){activate(event);mouseTracks(event)},timeout:opts.hoverIntent.timeout,out:function(event){inactivate(event);$this.unbind('mousemove.cluetip')}})}else{$this.bind('mouseenter.cluetip',function(event){activate(event);mouseTracks(event)}).bind('mouseleave.cluetip',function(event){inactivate(event);$this.unbind('mousemove.cluetip')})}$this.bind('mouseenter.cluetip',function(event){$this.attr('title','')}).bind('mouseleave.cluetip',function(event){$this.attr('title',$this.data('thisInfo').title)})}})};$.fn.cluetip.defaults={width:275,height:'auto',cluezIndex:97,positionBy:'auto',topOffset:15,leftOffset:15,local:false,localPrefix:null,hideLocal:true,attribute:'rel',titleAttribute:'title',splitTitle:'',escapeTitle:false,showTitle:true,cluetipClass:'default',hoverClass:'',waitImage:true,cursor:'help',arrows:false,dropShadow:true,dropShadowSteps:6,sticky:false,mouseOutClose:false,activation:'hover',clickThrough:false,tracking:false,delayedClose:0,closePosition:'top',closeText:'Close',truncate:0,fx:{open:'show',openSpeed:''},hoverIntent:{sensitivity:3,interval:50,timeout:0},onActivate:function(e){return true},onShow:function(ct,ci){},onHide:function(ct,ci){},ajaxCache:true,ajaxProcess:function(data){data=data.replace(/<(script|style|title)[^<]+<\/(script|style|title)>/gm,'').replace(/<(link|meta)[^>]+>/g,'');return data},ajaxSettings:{dataType:'html'},debug:false};var insertionType='appendTo',insertionElement='body';$.cluetip.setup=function(options){if(options&&options.insertionType&&(options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)){insertionType=options.insertionType}if(options&&options.insertionElement){insertionElement=options.insertionElement}}})(jQuery);

/*>>>>>>>>>> jquery.tablesorter.min.js <<<<<<<<<<*/

(function(j$){j$.extend({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,j$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if(j$.metadata&&(j$(j$headers[i]).metadata()&&j$(j$headers[i]).metadata().sorter)){p=getParserById(j$(j$headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,cells[i]);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,node){var l=parsers.length;for(var i=1;i<l;i++){if(parsers[i].is(j$.trim(getElementText(table.config,node)),table,node)){return parsers[i];}}return parsers[0];}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=table.tBodies[0].rows[i],cols=[];cache.row.push(j$(c));for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));}cols.push(i);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){if(!node)return"";var t="";if(config.textExtraction=="simple"){if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){t=node.childNodes[0].innerHTML;}else{t=node.innerHTML;}}else{if(typeof(config.textExtraction)=="function"){t=config.textExtraction(node);}else{t=j$(node).text();}}return t;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=j$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){rows.push(r[n[i][checkCell]]);if(!table.config.appender){var o=r[n[i][checkCell]];var l=o.length;for(var j=0;j<l;j++){tableBody[0].appendChild(o[j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){j$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=(j$.metadata)?true:false,tableHeadersRows=[];for(var i=0;i<table.tHead.rows.length;i++){tableHeadersRows[i]=0;};j$tableHeaders=j$("thead th",table);j$tableHeaders.each(function(index){this.count=0;this.column=index;this.order=formatSortingOrder(table.config.sortInitialOrder);if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(!this.sortDisabled){j$(this).addClass(table.config.cssHeader);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log(j$tableHeaders);}return j$tableHeaders;};function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if((j$.metadata)&&(j$(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){i=(v.toLowerCase()=="desc")?1:0;}else{i=(v==(0||1))?v:0;}return i;}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,j$headers,list,css){j$headers.removeClass(css[0]).removeClass(css[1]);var h=[];j$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=j$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,j$headers){var c=table.config;if(c.widthFixed){var colgroup=j$('<colgroup>');j$("tr:first td",table.tBodies[0]).each(function(){colgroup.append(j$('<col>').css('width',j$(this).width()));});j$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(getCachedSortType(table.config.parsers,c)=="text")?((order==0)?"sortText":"sortTextDesc"):((order==0)?"sortNumeric":"sortNumericDesc");var e="e"+i;dynamicExp+="var "+e+" = "+s+"(a["+c+"],b["+c+"]); ";dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function sortText(a,b){return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var j$this,j$document,j$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=j$.extend(this.config,j$.tablesorter.defaults,settings);j$this=j$(this);j$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,j$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);j$headers.click(function(e){j$this.trigger("sortStart");var totalRows=(j$this[0].tBodies[0]&&j$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var j$cell=j$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss(j$this[0],j$headers,config.sortList,sortCSS);appendToTable(j$this[0],multisort(j$this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});j$this.bind("update",function(){this.config.parsers=buildParserCache(this,j$headers);cache=buildCache(this);}).bind("sorton",function(e,list){j$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,j$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if(j$.metadata&&(j$(this).metadata()&&j$(this).metadata().sortlist)){config.sortList=j$(this).metadata().sortlist;}if(config.sortList.length>0){j$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){var DECIMAL='\\'+config.decimal;var exp='/(^[+]?0('+DECIMAL+'0+)?j$)|(^([-+]?[1-9][0-9]*)j$)|(^([-+]?((0?|[1-9][0-9]*)'+DECIMAL+'(0*[1-9][0-9]*)))j$)|(^[-+]?[1-9]+[0-9]*'+DECIMAL+'0+j$)/';return RegExp(exp).test(j$.trim(s));};this.clearTableBody=function(table){if(j$.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});j$.fn.extend({tablesorter:j$.tablesorter.construct});var ts=j$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return j$.trim(s.toLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return j$.tablesorter.isDigit(s,c);},format:function(s){return j$.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[Â£j$â?¬?.]/.test(s);},format:function(s){return j$.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}j$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return j$.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/j$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}j$/.test(s);},format:function(s){return j$.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%j$/.test(j$.trim(s));},format:function(s){return j$.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))j$/));},format:function(s){return j$.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"j$3/j$1/j$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"j$3/j$2/j$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"j$1/j$2/j$3");}return j$.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))j$/.test(s);},format:function(s){return j$.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return j$(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}j$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]).end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);if(table.config.debug){j$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);

/*>>>>>>>>>> jquery.jmc_resizr.js <<<<<<<<<<*/
/*
 * Pagery (jmc_resizr) - a jQuery plugin for binding image sizes to a parent element
 * Examples and documentation at: http://code.euphemize.net/jQuery/jmc_resizr/
 * Version: 0.1 (2010-03-04)
 * Copyright (c) 2010 Joel Courtney
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Requires: jQuery v1.3.2 or later
*/
(function($) {
    $.fn.jmc_resizr = function(settings) {

		var win = $(window);

        var defaults = {
            cropType : 'full',
			binding : {
				vertical : 'center',
				horizontal : 'center'
			},
            followBrowserSize :  true,
			parentElement : $('body')
        };

		var opts = {
			settings: $.extend({}, defaults, settings)
		};

		var resizeNode = function(el) {
			el = $(el);
			ratio = el.height() / el.width();

			var win_h = win.height(), win_w = win.width();
			// TODO: Update with binding to a parent element
			// if(defaults.parentElement != $('body')) {
			// 	win_h = win.height(), win_w = win.width();
			// }

			var settings = $.extend({},opts.settings);
			
			switch(settings.cropType) {
				case 'fit':
					h = win_h;
					w = win_w;
					break;
				case 'height':
					h = win_h;
					w = win_h / ratio;
					break;
				case 'width':
					h = win_w * ratio;
					w = win_w;
					break;
				case 'fill_outer':
					if(win_h/win_w <= ratio) {
						// Go by width
						h = win_w * ratio;
						w = win_w;
					} else {
						// Go by height
						h = win_h;
						w = win_h / ratio;
					}
					break;
				case 'full':
				default:
					if(win_h/win_w >= ratio) {
						// Go by width
						h = win_w * ratio;
						w = win_w;
					} else {
						// Go by height
						h = win_h;
						w = win_h / ratio;
					}
			}
			h = Math.ceil(h);
			w = Math.ceil(w);
			switch(settings.binding.vertical) {
				case 'top':
					t = 0;
					break;
				case 'bottom':
					t = (win_h - h);
					break;
				case 'center':
				default:
					t = (win_h - h)/2;
					break;
			}
			switch(settings.binding.horizontal) {
				case 'left':
					l = 0;
					break;
				case 'right':
					l = (win_w - w);
					break;
				case 'center':
				default:
					l = (win_w - w)/2;
					break;
			}
			el.css({'height':h, 'width':w, 'position': 'absolute', 'top': t, 'left': l});					
		};

        var followBrowserResize = function(el) {
			if ($(el) == null) {
				return;
			}
			resizeNode(el);
        };

	    return this.each(function() { 
			// Check that it is an image
			if (this.nodeName === 'IMG') {
				// Undertake check load state
				$(this).load(function () {
					resizeNode(this);
					var settings = $.extend({},opts.settings);
			        if (settings.followBrowserSize) {
						el = this;
			            $(window).bind('resize', function() {
							followBrowserResize(el);
			            });
			        }
				}).error(function () {
	            // notify the user that the asset could not be loaded
					alert("Could not load!"+$(this).attr('src'));
		        }).attr('src', $(this).attr('src'));
	        } else {
				resizeNode(this);
				var settings = $.extend({},opts.settings);
		        if (settings.followBrowserSize) {
					el = this;
		            $(window).bind('resize', function() {
						followBrowserResize(el);
		            });
		        }
			}
	    });
	};
})(jQuery);

/*>>>>>>>>>> jquery.printElement.js <<<<<<<<<<*/
/*
* Print Element Plugin 1.1
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
*  jQuery plugin page : http://plugins.jquery.com/project/printElement 
*  Wiki : http://wiki.github.com/erikzaadi/jQueryPlugins/jqueryprintelement 
*  Home Page : http://erikzaadi.github.com/jQueryPlugins/jQuery.printElement 
*  
*  Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
*  For their great contributions!
* 
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*   For Detail options got to: http://wiki.github.com/erikzaadi/jQueryPlugins/jqueryprintelement-options
*   
*   Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
;
(function($){
    $.fn.printElement = function(options){
        var mainOptions = $.extend({}, $.fn.printElement.defaults, options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
        if (mainOptions.printMode == 'iframe') {
            if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) 
                mainOptions.printMode = 'popup';
        }
        //Remove previously printed iframe if exists
        $("[id^='printElement_']").remove();
        
        return this.each(function(){
            //Support Metadata Plug-in if available
            var opts = $.meta ? $.extend({}, mainOptions, $this.data()) : mainOptions;
            _printElement($(this), opts);
        });
    };
    $.fn.printElement.defaults = {
        printMode: 'iframe', //Usage : iframe / popup
        pageTitle: '', //Print Page Title
        overrideElementCSS: null,
        /* Can be one of the following 3 options:
         * 1 : boolean (pass true for stripping all css linked)
         * 2 : array of $.fn.printElement.cssElement (s)
         * 3 : array of strings with paths to alternate css files (optimized for print)
         */
        printBodyOptions: {
            styleToAdd: 'padding:10px;margin:10px;', //style attributes to add to the body of print document
            classNameToAdd: '' //css class to add to the body of print document
        },
        leaveOpen: false, // in case of popup, leave the print page open or not
        iframeElementOptions: {
            styleToAdd: 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            classNameToAdd: '' //css class to add to the iframe element
        }
    };
    $.fn.printElement.cssElement = {
        href: '',
        media: ''
    };
    function _printElement(element, opts){
        //Create markup to be printed
        var html = _getMarkup(element, opts);
        
        var popupOrIframe = null;
        var documentToWriteTo = null;
        if (opts.printMode.toLowerCase() == 'popup') {
            popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
            documentToWriteTo = popupOrIframe.document;
        }
        else {
            //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
            var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
            $(iframe).attr({
                style: opts.iframeElementOptions.styleToAdd,
                id: printElementID,
                className: opts.iframeElementOptions.classNameToAdd,
                frameBorder: 0,
                scrolling: 'no',
                src: 'about:blank'
            });
            document.body.appendChild(iframe);
            documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
            if (documentToWriteTo.document) 
                documentToWriteTo = documentToWriteTo.document;
            iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
            popupOrIframe = iframe.contentWindow || iframe;
        }
        focus();
        documentToWriteTo.open();
        documentToWriteTo.write(html);
        documentToWriteTo.close();
        _callPrint(popupOrIframe);
    };
    
    function _callPrint(element){
        if (element && element.printPage) 
            element.printPage();
        else 
            setTimeout(function(){
                _callPrint(element);
            }, 50);
    }
    
    function _getElementHTMLIncludingFormElements(element){
        var $element = $(element);
        //Radiobuttons and checkboxes
        $(":checked", $element).each(function(){
            this.setAttribute('checked', 'checked');
        });
        //simple text inputs
        $("input[type='text']", $element).each(function(){
            this.setAttribute('value', $(this).val());
        });
        $("select", $element).each(function(){
            var $select = $(this);
            $("option", $select).each(function(){
                if ($select.val() == $(this).val()) 
                    this.setAttribute('selected', 'selected');
            });
        });
        $("textarea", $element).each(function(){
            //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
            var value = $(this).attr('value');
            if ($.browser.mozilla) 
                this.firstChild.textContent = value;
            else 
                this.innerHTML = value;
        });
        //http://dbj.org/dbj/?p=91
        var elementHtml = $('<div></div>').append($element.clone()).html();
        return elementHtml;
    }
    
	//http://github.com/erikzaadi/jQueryPlugins/issues#issue/3
    function _getBaseHref(){
		return window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "") + window.location.pathname;
	}
    
        
    function _getMarkup(element, opts){
        var $element = $(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);
        
        var html = new Array();
        html.push('<html><head><title>' + opts.pageTitle + '</title>');
        if (opts.overrideElementCSS) {
            if (opts.overrideElementCSS.length > 0) {
                for (var x = 0; x < opts.overrideElementCSS.length; x++) {
                    var current = opts.overrideElementCSS[x];
                    if (typeof(current) == 'string') 
                        html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
                    else 
                        html.push('<link type="text/css" rel="stylesheet" href="' + current.href + '" media="' + current.media + '" >');
                }
            }
        }
        else {
            $(document).find("link").filter(function(){
                return $(this).attr("rel").toLowerCase() == "stylesheet";
            }).each(function(){
                html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
            });
        }
        //Ensure that relative links work
        html.push('<base href="' + _getBaseHref() + '" />');
        html.push('</head><body style="' + opts.printBodyOptions.styleToAdd + '" class="' + opts.printBodyOptions.classNameToAdd + '">');
        html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
        html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts.leaveOpen && opts.printMode.toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
        html.push('</body></html>');
        
        return html.join('');
    };
    })(jQuery);

/*>>>>>>>>>> jquery.easing.1.3.js <<<<<<<<<<*/
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
    def: 'easeOutQuad',
    swing: function (x, t, b, c, d) {
        //alert(jQuery.easing.default);
        return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
    },
    easeInQuad: function (x, t, b, c, d) {
        return c*(t/=d)*t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c *(t/=d)*(t-2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInCubic: function (x, t, b, c, d) {
        return c*(t/=d)*t*t + b;
    },
    easeOutCubic: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t + 1) + b;
    },
    easeInOutCubic: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t + b;
        return c/2*((t-=2)*t*t + 2) + b;
    },
    easeInQuart: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t + b;
    },
    easeOutQuart: function (x, t, b, c, d) {
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeInOutQuart: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    easeInQuint: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t*t + b;
    },
    easeOutQuint: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t*t*t + 1) + b;
    },
    easeInOutQuint: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
        return c/2*((t-=2)*t*t*t*t + 2) + b;
    },
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t/d * (Math.PI/2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
    },
    easeInExpo: function (x, t, b, c, d) {
        return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
    },
    easeOutExpo: function (x, t, b, c, d) {
        return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
    },
    easeInOutExpo: function (x, t, b, c, d) {
        if (t==0) return b;
        if (t==d) return b+c;
        if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
        return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
    },
    easeInCirc: function (x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
    },
    easeOutCirc: function (x, t, b, c, d) {
        return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
    },
    easeInOutCirc: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
        return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
    },
    easeInElastic: function (x, t, b, c, d) {
        var s=1.70158;var p=0;var a=c;
        if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
        if (a < Math.abs(c)) { a=c; var s=p/4; }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    easeOutElastic: function (x, t, b, c, d) {
        var s=1.70158;var p=0;var a=c;
        if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
        if (a < Math.abs(c)) { a=c; var s=p/4; }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },
    easeInOutElastic: function (x, t, b, c, d) {
        var s=1.70158;var p=0;var a=c;
        if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
        if (a < Math.abs(c)) { a=c; var s=p/4; }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
    },
    easeInBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    easeOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    },
    easeInOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158; 
        if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    easeInBounce: function (x, t, b, c, d) {
        return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
    },
    easeOutBounce: function (x, t, b, c, d) {
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
        } else {
            return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
        }
    },
    easeInOutBounce: function (x, t, b, c, d) {
        if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
        return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
    }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

/*>>>>>>>>>> jquery.selectboxes.js <<<<<<<<<<*/
/*
 *
 * Copyright (c) 2006-2010 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.2.5
 * Demo: http://www.texotela.co.uk/code/jquery/select/
 *
 *
 */
 
;(function($) {
 
/**
 * Adds (single/multiple) options to a select box (or series of select boxes)
 *
 * @name     addOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
 * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
 * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
 *
 */
$.fn.addOption = function()
{
	var add = function(el, v, t, sO, index)
	{
		var option = document.createElement("option");
		option.value = v, option.text = t;
		// get options
		var o = el.options;
		// get number of options
		var oL = o.length;
		if(!el.cache)
		{
			el.cache = {};
			// loop through existing options, adding to cache
			for(var i = 0; i < oL; i++)
			{
				el.cache[o[i].value] = i;
			}
		}
		if (index || index == 0)
		{
 			// we're going to insert these starting  at a specific index...
			// this has the side effect of el.cache[v] being the 
			// correct value for the typeof check below
			var ti = option;
			for(var ii =index; ii <= oL; ii++)
			{
				var tmp = el.options[ii];
				el.options[ii] = ti;
				o[ii] = ti;
				el.cache[o[ii].value] = ii;
				ti = tmp;
			}
		}
    
		// add to cache if it isn't already
		if(typeof el.cache[v] == "undefined") el.cache[v] = oL;
		el.options[el.cache[v]] = option;
		if(sO)
		{
			option.selected = true;
		}
	};
	
	var a = arguments;
	if(a.length == 0) return this;
	// select option when added? default is true
	var sO = true;
	// multiple items
	var m = false;
	// other variables
	var items, v, t;
	if(typeof(a[0]) == "object")
	{
		m = true;
		items = a[0];
	}
	if(a.length >= 2)
	{
		if(typeof(a[1]) == "boolean")
		{
			sO = a[1];
			startindex = a[2];
		}
		else if(typeof(a[2]) == "boolean")
		{
			sO = a[2];
			startindex = a[1];
		}
		else
		{
			startindex = a[1];
		}
		if(!m)
		{
			v = a[0];
			t = a[1];
		}
	}
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			if(m)
			{
				for(var item in items)
				{
					add(this, item, items[item], sO, startindex);
					startindex += 1;
				}
			}
			else
			{
				add(this, v, t, sO, startindex);
			}
		}
	);
	return this;
};

/**
 * Add options via ajax
 *
 * @name     ajaxAddOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String url      Page to get options from (must be valid JSON)
 * @param    Object params   (optional) Any parameters to send with the request
 * @param    Boolean select  (optional) Select the added options, default true
 * @param    Function fn     (optional) Call this function with the select object as param after completion
 * @param    Array args      (optional) Array with params to pass to the function afterwards
 * @example  $("#myselect").ajaxAddOption("myoptions.php");
 * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"});
 * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"}, false, sortoptions, [{"dir": "desc"}]);
 *
 */
$.fn.ajaxAddOption = function(url, params, select, fn, args)
{
	if(typeof(url) != "string") return this;
	if(typeof(params) != "object") params = {};
	if(typeof(select) != "boolean") select = true;
	this.each(
		function()
		{
			var el = this;
			$.getJSON(url,
				params,
				function(r)
				{
					$(el).addOption(r, select);
					if(typeof fn == "function")
					{
						if(typeof args == "object")
						{
							fn.apply(el, args);
						} 
						else
						{
							fn.call(el);
						}
					}
				}
			);
		}
	);
	return this;
};

/**
 * Removes an option (by value or index) from a select box (or series of select boxes)
 *
 * @name     removeOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String|RegExp|Number what  Option to remove
 * @param    Boolean selectedOnly       (optional) Remove only if it has been selected (default false)   
 * @example  $("#myselect").removeOption("Value"); // remove by value
 * @example  $("#myselect").removeOption(/^val/i); // remove options with a value starting with 'val'
 * @example  $("#myselect").removeOption(/./); // remove all options
 * @example  $("#myselect").removeOption(/./, true); // remove all options that have been selected
 * @example  $("#myselect").removeOption(0); // remove by index
 * @example  $("#myselect").removeOption(["myselect_1","myselect_2"]); // values contained in passed array
 *
 */
$.fn.removeOption = function()
{
	var a = arguments;
	if(a.length == 0) return this;
	var ta = typeof(a[0]);
	var v, index;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(ta == "string" || ta == "object" || ta == "function" )
	{
		v = a[0];
		// if an array, remove items
		if(v.constructor == Array)
		{
			var l = v.length;
			for(var i = 0; i<l; i++)
			{
				this.removeOption(v[i], a[1]); 
			}
			return this;
		}
	}
	else if(ta == "number") index = a[0];
	else return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			// clear cache
			if(this.cache) this.cache = null;
			// does the option need to be removed?
			var remove = false;
			// get options
			var o = this.options;
			if(!!v)
			{
				// get number of options
				var oL = o.length;
				for(var i=oL-1; i>=0; i--)
				{
					if(v.constructor == RegExp)
					{
						if(o[i].value.match(v))
						{
							remove = true;
						}
					}
					else if(o[i].value == v)
					{
						remove = true;
					}
					// if the option is only to be removed if selected
					if(remove && a[1] === true) remove = o[i].selected;
					if(remove)
					{
						o[i] = null;
					}
					remove = false;
				}
			}
			else
			{
				// only remove if selected?
				if(a[1] === true)
				{
					remove = o[index].selected;
				}
				else
				{
					remove = true;
				}
				if(remove)
				{
					this.remove(index);
				}
			}
		}
	);
	return this;
};

/**
 * Sort options (ascending or descending) in a select box (or series of select boxes)
 *
 * @name     sortOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    Boolean ascending   (optional) Sort ascending (true/undefined), or descending (false)
 * @example  // ascending
 * $("#myselect").sortOptions(); // or $("#myselect").sortOptions(true);
 * @example  // descending
 * $("#myselect").sortOptions(false);
 *
 */
$.fn.sortOptions = function(ascending)
{
	// get selected values first
	var sel = $(this).selectedValues();
	var a = typeof(ascending) == "undefined" ? true : !!ascending;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			// create an array for sorting
			var sA = [];
			// loop through options, adding to sort array
			for(var i = 0; i<oL; i++)
			{
				sA[i] = {
					v: o[i].value,
					t: o[i].text
				}
			}
			// sort items in array
			sA.sort(
				function(o1, o2)
				{
					// option text is made lowercase for case insensitive sorting
					o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase();
					// if options are the same, no sorting is needed
					if(o1t == o2t) return 0;
					if(a)
					{
						return o1t < o2t ? -1 : 1;
					}
					else
					{
						return o1t > o2t ? -1 : 1;
					}
				}
			);
			// change the options to match the sort array
			for(var i = 0; i<oL; i++)
			{
				o[i].text = sA[i].t;
				o[i].value = sA[i].v;
			}
		}
	).selectOptions(sel, true); // select values, clearing existing ones
	return this;
};
/**
 * Selects an option by value
 *
 * @name     selectOptions
 * @author   Mathias Bank (http://www.mathias-bank.de), original function
 * @author   Sam Collett (http://www.texotela.co.uk), addition of regular expression matching
 * @type     jQuery
 * @param    String|RegExp|Array value  Which options should be selected
 * can be a string or regular expression, or an array of strings / regular expressions
 * @param    Boolean clear  Clear existing selected options, default false
 * @example  $("#myselect").selectOptions("val1"); // with the value 'val1'
 * @example  $("#myselect").selectOptions(["val1","val2","val3"]); // with the values 'val1' 'val2' 'val3'
 * @example  $("#myselect").selectOptions(/^val/i); // with the value starting with 'val', case insensitive
 *
 */
$.fn.selectOptions = function(value, clear)
{
	var v = value;
	var vT = typeof(value);
	// handle arrays
	if(vT == "object" && v.constructor == Array)
	{
		var $this = this;
		$.each(v, function()
			{
      				$this.selectOptions(this, clear);
    			}
		);
	};
	var c = clear || false;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if(o[i].value.match(v))
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
				else
				{
					if(o[i].value == v)
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
			}
		}
	);
	return this;
};

/**
 * Copy options to another select
 *
 * @name     copyOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @param    String to  Element to copy to
 * @param    String which  (optional) Specifies which options should be copied - 'all' or 'selected'. Default is 'selected'
 * @example  $("#myselect").copyOptions("#myselect2"); // copy selected options from 'myselect' to 'myselect2'
 * @example  $("#myselect").copyOptions("#myselect2","selected"); // same as above
 * @example  $("#myselect").copyOptions("#myselect2","all"); // copy all options from 'myselect' to 'myselect2'
 *
 */
$.fn.copyOptions = function(to, which)
{
	var w = which || "selected";
	if($(to).size() == 0) return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(w == "all" || (w == "selected" && o[i].selected))
				{
					$(to).addOption(o[i].value, o[i].text);
				}
			}
		}
	);
	return this;
};

/**
 * Checks if a select box has an option with the supplied value
 *
 * @name     containsOption
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Boolean|jQuery
 * @param    String|RegExp value  Which value to check for. Can be a string or regular expression
 * @param    Function fn          (optional) Function to apply if an option with the given value is found.
 * Use this if you don't want to break the chaining
 * @example  if($("#myselect").containsOption("val1")) alert("Has an option with the value 'val1'");
 * @example  if($("#myselect").containsOption(/^val/i)) alert("Has an option with the value starting with 'val'");
 * @example  $("#myselect").containsOption("val1", copyoption).doSomethingElseWithSelect(); // calls copyoption (user defined function) for any options found, chain is continued
 *
 */
$.fn.containsOption = function(value, fn)
{
	var found = false;
	var v = value;
	var vT = typeof(v);
	var fT = typeof(fn);
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return fT == "function" ? this: found;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// option already found
			if(found && fT != "function") return false;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if (o[i].value.match(v))
					{
						found = true;
						if(fT == "function") fn.call(o[i], i);
					}
				}
				else
				{
					if (o[i].value == v)
					{
						found = true;
						if(fT == "function") fn.call(o[i], i);
					}
				}
			}
		}
	);
	return fT == "function" ? this : found;
};

/**
 * Returns values which have been selected
 *
 * @name     selectedValues
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Array
 * @example  $("#myselect").selectedValues();
 *
 */
$.fn.selectedValues = function()
{
	var v = [];
	this.selectedOptions().each(
		function()
		{
			v[v.length] = this.value;
		}
	);
	return v;
};

/**
 * Returns text which has been selected
 *
 * @name     selectedTexts
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     Array
 * @example  $("#myselect").selectedTexts();
 *
 */
$.fn.selectedTexts = function()
{
	var t = [];
	this.selectedOptions().each(
		function()
		{
			t[t.length] = this.text;
		}
	);
	return t;
};

/**
 * Returns options which have been selected
 *
 * @name     selectedOptions
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").selectedOptions();
 *
 */
$.fn.selectedOptions = function()
{
	return this.find("option:selected");
};

})(jQuery);

/*>>>>>>>>>> superfish.js <<<<<<<<<<*/

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);


/*>>>>>>>>>> typeahead.js <<<<<<<<<<*/
function typeAHead(){
	var loc = {};
	loc.matching = [];
	loc.searchTerm = j$("#searchTerm").val();
	loc.storeId = j$("#storeId").val();
	//loc.storeId = 30;
	loc.solr = j$("#solr").val();
	
	if ( loc.searchTerm.length > 0 ){
		loc.searchTerm = escapeRegExp({text:loc.searchTerm});
		
		if ( loc.searchTerm.length > 1 ){
			strUrl = siteUrl + 'com/b2c/search/solrAutoComplete.cfc?term=' + loc.searchTerm + '&storeId=' + loc.storeId + '&solr=' + loc.solr;
			
			j$.ajax({
				url: strUrl ,
				data: { method:'GET_SOLR_AUTOCOMPLETE' },
				type: 'GET',
				dataType: 'JSON',
				async: true,
				success: function(json) {
					var myObject = eval('(' + json + ')');
					loc.matching = myObject;
					if (loc.matching.length > 0) {
						displayMatching({arr:loc.matching, searchTerm:loc.searchTerm});
					} else {
						hideTypeAHead();
					}
				}
			});
		}
		
	} else {
		hideTypeAHead();
	}
}

function escapeRegExp(arguments){
	var loc = {};
	
    loc.specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
	loc.sRE = new RegExp('(\\' + loc.specials.join('|\\') + ')', 'g');

	return arguments.text.replace(loc.sRE, '\\$1');
} 

function displayMatching(arguments) {
	var loc = {};
	
	loc.pattern = new RegExp( "(" + arguments.searchTerm + ")", "gi" ); 
	loc.pattern.compile(loc.pattern);
	
	loc.arrDisplay = [];
	
	for ( loc.i = 0; loc.i < arguments.arr.length; loc.i++ ){
		
		loc.str = arguments.arr[ loc.i ];
		loc.arrDisplay.push(loc.str.replace(loc.pattern, "<span class='typeaheadhl'>$1</span>"));
	}
	
	j$("#matching").html("<ul><li>" + loc.arrDisplay.join("</li><li>") + "</li></ul>").show();
	j$("#matching li").bind("click", function(){
		j$("#searchTerm").val(j$(this).text());
		hideTypeAHead();
		submitSearchFormOnTop();
	});
	j$("#matching").bind("blur", function(){
		setTimeout( function() { hideTypeAHead(); }, 200 )
	});
}

j$(function() {
	j$("#searchTerm")
		.bind("keyup", function(){typeAHead()})
		.bind("focus", function(){typeAHead()})
		//.bind("blur", function(){ setTimeout( function() { hideTypeAHead(); }, 200 ) });
});

function hideTypeAHead(){
	j$("#matching").hide();
}


/*>>>>>>>>>> jquery.jqzoom-1.0.1.js <<<<<<<<<<*/
/*
 * JQZoom Evolution 1.0.1 - Javascript Image magnifier
 *
 * Copyright (c) Engineer Renzi Marco(www.mind-projects.it)
 *
 * $Date: 12-12-2008
 *
 *	ChangeLog:
 *  
 * $License : GPL,so any change to the code you should copy and paste this section,and would be nice to report this to me(renzi.mrc@gmail.com).
 */
(function($)
{
    $.fn.jqzoom = function(options)
    {
        var settings = {
            zoomType: 'standard', //standard/reverse/innerzoom
            zoomWidth: 200,		//zoomed width default width
            zoomHeight: 200,		//zoomed div default width
            xOffset: 10,		//zoomed div default offset
            yOffset: 0,
            position: "right" ,//zoomed div default position,offset position is to the right of the image
            lens:true, //zooming lens over the image,by default is 1;
			lensReset : false,
			imageOpacity: 0.2,
			title : true,
			alwaysOn: false,
			showEffect: 'show',
			hideEffect: 'hide',
			fadeinSpeed: 'fast',
			fadeoutSpeed: 'slow',
			preloadImages :true,
			showPreload: true,
			preloadText : 'Loading zoom',
			preloadPosition : 'center'   //bycss
        };

			//extending options
			options = options || {};
        	$.extend(settings, options);


		return this.each(function()
		{
			var a = $(this);
			var aTitle = a.attr('title'); //variabile per memorizzare il titolo href
			$(a).removeAttr('title');
			$(a).css('outline-style','none');


			var img = $("img", this);
			var imageTitle = img.attr('title');
			img.removeAttr('title');	//variabile per memorizzare il titolo immagine


			var smallimage = new Smallimage( img );
			var smallimagedata = {};
			//imageborder
			var btop = 0;
			var bleft = 0;

			var loader = null;     //variabile per memorizzare oggetto loader
			loader = new Loader();

			var ZoomTitle = (trim(aTitle).length > 0) ? aTitle :
			(trim(imageTitle).length > 0) ? imageTitle : null;  //setting zoomtitle
			var ZoomTitleObj = new zoomTitle();

			var largeimage = new Largeimage( a[0].href );

			var lens = new Lens();
			var lensdata = {};
			//lensborder



			var largeimageloaded = false;
			var scale = {}; //rapporto tra immagine grande e piccola scale.x/scale.y
			var stage = null; // quadrato che mostra l'immagine ingrandita
			var running = false; // running = true quando si verifica l'evento che mostra lo zoom(adesso mouseover).
			var mousepos = {};
			var firstime = 0;
			var preloadshow = false;
			var isMouseDown = false;
			var dragstatus = false
			//loading smallimagedata
			smallimage.loadimage();

			//ritorna false al click dell href
			$(this).click(function(){return false;});

			//se settato alwaysOn attivo lo Zoom e lo mostro.

			//attivo al mouseover
			$(this).hover(function(e)
			{
				mousepos.x = e.pageX;
				mousepos.y	= e.pageY;
				activate();
			},function()
			{
				deactivate();
			});


			//ALWAYS ON
			if(settings.alwaysOn)
			{
				setTimeout(function(){activate();},150);
			}


			function activate()
			{

				if ( !running ) {

					//finding border
					smallimage.findborder();

					running = true;

					//rimuovo il titolo al mouseover
					imageTitle = img.attr('title');
					img.removeAttr('title');
					aTitle = a.attr('title');
					$(a).removeAttr('title');

					//se non cè creo l'oggetto largeimage
					if (!largeimage || $.browser.safari) {
						largeimage = new Largeimage( a[0].href );
					}

					//se l'immagine grande non è stata caricata la carico
					if(!largeimageloaded || $.browser.safari)
					{
						largeimage.loadimage();
					}else
					{
					//after preload
						if(settings.zoomType != 'innerzoom')
						{
							stage = new Stage();
							stage.activate();
						}
						lens = new Lens;
						lens.activate();
					}

					//hack per MAC
				/*	if($.browser.safari)
					{
						if(settings.zoomType != 'innerzoom') //se innerzoom non mostro la finestra dello zoom
						{
							stage = new Stage();
							stage.activate();
						}
						if($('div.jqZoomPup').length <= 0)
						{
						lens = new Lens();
						}
						//if(settings.zoomType == 'innerzoom'){lens = new Lens()};
						lens.activate();
						(settings.alwaysOn) ? lens.center() : lens.setposition(null);
					}
					*/
					a[0].blur();
					//alert($('div.jqZoomPup').length);
					return false;
				}




			}

			function deactivate()
			{
				if(settings.zoomType == 'reverse' &&  !settings.alwaysOn)
				{
					img.css({'opacity' : 1});
				}

				if(!settings.alwaysOn)
				{
					//resetting parameters
					running = false;
					largeimageloaded = false;
					$(lens.node).unbind('mousemove');
					lens.remove();
					if($('div.jqZoomWindow').length >0)
					{
						stage.remove();
					}
					if($('div.jqZoomTitle').length > 0)
					{
						ZoomTitleObj.remove();
					}
					//resetting title
					img.attr('title',imageTitle);
					a.attr('title',aTitle);
					$().unbind();

					a.unbind('mousemove');
					//resetto il parametro che mi dice che è la prima volta che mostor lo zoom
					firstime = 0;
					//remove ieiframe
					if(jQuery('.zoom_ieframe').length > 0)
					{
						jQuery('.zoom_ieframe').remove();
					}
				}else
				{
					if(settings.lensReset)
					{
						switch(settings.zoomType)
						{
							case 'innerzoom':
							largeimage.setcenter();
							break;
							default:
							lens.center();
							break;
						}
					}
				}

				//non so se serve da provare
				if(settings.alwaysOn)
				{
					activate();
				}
			};





		//smallimage
		function Smallimage( image )
		{
			this.node = image[0];

			this.loadimage = function() {
				this.node.src = image[0].src;
			};
			this.findborder = function()
			{
				var bordertop = '';
				bordertop = $(img).css('border-top-width');
				btop = '';
				var borderleft = '';
				borderleft = $(img).css('border-left-width');
				bleft = '';
				/*if($.browser.msie)
				{
					var temp = bordertop.split(' ');

					bordertop = temp[1];
					var temp = borderleft.split(' ');
					borderleft = temp[1];
				}*/

				if(bordertop)
				{
					for(i=0;i<3;i++)
					{
						var x = [];
						x = bordertop.substr(i,1);

						if(isNaN(x) == false)
						{
							btop = btop +''+ bordertop.substr(i,1);
						}else
						{
							break;
						}
					}
				}

				if(borderleft)
				{
					for(i=0;i<3;i++)
					{
						if(!isNaN(borderleft.substr(i,1)))
						{
							bleft = bleft + borderleft.substr(i,1)
						}else
						{
							break;
						}
					}
				}
				btop = (btop.length > 0) ? eval(btop) : 0;
				bleft = (bleft.length > 0) ? eval(bleft) : 0;


			}
			this.node.onload = function()
			{
				//setto il cursor e la posizione dell'href


				a.css({'cursor':'crosshair','display':'block'});

				if(a.css('position')!= 'absolute' && a.parent().css('position'))
				{
					a.css({'cursor':'crosshair','position':'relative','display':'block'});
				}
				if(a.parent().css('position') != 'absolute')
				{
					a.parent().css('position','relative');
					//a.css('position','relative');
				}
				else{
				//a.css('position','relative');
				}
				if($.browser.safari || $.browser.opera)
				{
					$(img).css({position:'absolute',top:'0px',left:'0px'});
				}
				/*if(a.css('position')!= 'absolute' && a.parent().css('position'))
				{
					a.css({'cursor':'crosshair','position':'relative','display':'block'});
				}
				if(a.parent().css('position') != 'absolute')
				{
					alert('in');
					a.parent().css('position','relative');
					//a.css('position','relative');
				}
				else{
				//a.css('position','relative');
				}*/



				/*
				if(a.parent().css('position') != 'relative' && a.css('position') != 'absolute')
				{
				a.css({'cursor':'crosshair','position':'relative','display':'block'});
				}*/

				//al docuemnt ready viene caricato l'src quindi viene azionato l'onload e carico tutti i dati
				smallimagedata.w = $( this ).width();
				smallimagedata.h = $( this ).height();


				//non viene fatta assegnazione alla variabile globale
				smallimagedata.h = $( this ).height();
				smallimagedata.pos = $( this ).offset();
				smallimagedata.pos.l = $( this ).offset().left;
				smallimagedata.pos.t = $( this ).offset().top;
				smallimagedata.pos.r = smallimagedata.w + smallimagedata.pos.l;
				smallimagedata.pos.b = smallimagedata.h + smallimagedata.pos.t;

				//per sicurezza setto l'altezza e la width dell'href
				a.height(smallimagedata.h);
				a.width(smallimagedata.w);


				//PRELOAD IMAGES
				if(settings.preloadImages)
				{
					largeimage.loadimage();
				}



			};



			return this;
		};



		//Lens
		function Lens()
		{


			//creating element and adding class
			this.node = document.createElement("div");
			$(this.node).addClass('jqZoomPup');

			this.node.onerror = function() {
				$( lens.node ).remove();
				lens = new Lens();
				lens.activate() ;
			};




			//funzione privata per il caricamento dello zoom
			this.loadlens = function()
			{


				switch(settings.zoomType)
				{
					case 'reverse':
						this.image = new Image();
						this.image.src = smallimage.node.src; // fires off async
						this.node.appendChild( this.image );
						$( this.node ).css({'opacity' : 1});
					break;
					case 'innerzoom':

						this.image = new Image();
						this.image.src = largeimage.node.src; // fires off async
						this.node.appendChild( this.image );
						$( this.node ).css({'opacity' : 1});
					break
					default:
					break;
				}



				switch(settings.zoomType)
				{
					case 'innerzoom':
						lensdata.w = smallimagedata.w;
						lensdata.h = smallimagedata.h;
					break;
					default:
						lensdata.w = (settings.zoomWidth)/scale.x;
						lensdata.h = (settings.zoomHeight)/scale.y;
					break;
				}

			$( this.node ).css({
					width: lensdata.w + 'px',
					height: lensdata.h + 'px',
					position: 'absolute',
					/*cursor: 'crosshair',*/
					display: 'none',
					//border: '1px solid blue'
					borderWidth: 1+'px'
				});
			a.append(this.node);
			}
			return this;
		};

		Lens.prototype.activate = function()
		{
			//carico la lente
			this.loadlens();

			switch(settings.zoomType)
			{
				case 'reverse':
					img.css({'opacity' : settings.imageOpacity});

					(settings.alwaysOn) ? lens.center() : lens.setposition(null);
					//lens.center();
					//bindo ad a il mousemove della lente
					a.bind( 'mousemove', function(e)
					{
						mousepos.x = e.pageX;
						mousepos.y = e.pageY;
						lens.setposition( e );
					});
				break;
				case 'innerzoom':

					//	lens = new Lens();
					//	lens.activate();

					$( this.node ).css({top : 0 ,left: 0});
				   	if(settings.title)
					{
						ZoomTitleObj.loadtitle();
					}

					largeimage.setcenter();

				   	a.bind( 'mousemove', function(e)
				   	{
						mousepos.x = e.pageX;
						mousepos.y = e.pageY;
						largeimage.setinner( e );

					/*if(settings.zoomType == 'innerzoom' && running)
					{
						$(a).mousemove(function(){
							if($('div.jqZoomPup').length <= 0)
							{
								lens = new Lens();
								lens.activate();
							}
						});
					}*/

						/*if($('div.jqZoomPup').length <= 0)
							{
								lens = new Lens();
								lens.activate();
							}*/

					});
				break;
				default:
					/*$(document).mousemove(function(e){
					if(isMouseDown && dragstatus != false){
					lens.setposition( e );
					}
					});
					lens.center()


					dragstatus = 'on'
					$(document).mouseup(function(e){
					if(isMouseDown && dragstatus != false){
						isMouseDown = false;
						dragstatus = false;

					}
					});

					$(this.node).mousedown(function(e){
					$('div.jqZoomPup').css("cursor", "move");
					$(this.node).css("position", "absolute");

				// set z-index
					$(this.node).css("z-index", parseInt( new Date().getTime()/1000 ));
					if($.browser.safari)
					{
						$(a).css("cursor", "move");
					}
					isMouseDown    = true;
					dragstatus = 'on';
					lens.setposition( e );
					});
					*/


					(settings.alwaysOn) ? lens.center() : lens.setposition(null);

					//bindo ad a il mousemove della lente
					$(a).bind( 'mousemove', function(e)
					{

						mousepos.x = e.pageX;
						mousepos.y = e.pageY;
						lens.setposition( e );
					});

				break;
			}


			return this;
		};

		Lens.prototype.setposition = function( e)
		{


			if(e)
			{
				mousepos.x = e.pageX;
				mousepos.y	= e.pageY;
			}

			if(firstime == 0)
			{
			 	var lensleft = (smallimagedata.w)/2 - (lensdata.w)/2 ;
			 	var lenstop = (smallimagedata.h)/2 - (lensdata.h)/2 ;
				//ADDED

				$('div.jqZoomPup').show()
				if(settings.lens)
				{
					this.node.style.visibility = 'visible';
				}
				else
				{
					this.node.style.visibility = 'hidden';
					$('div.jqZoomPup').hide();
				}
				//ADDED
				firstime = 1;

			}else
			{
				var lensleft = mousepos.x - smallimagedata.pos.l - (lensdata.w)/2 ;
				var lenstop = mousepos.y - smallimagedata.pos.t -(lensdata.h)/2 ;
			}


				//a sinistra
				if(overleft())
				{
					lensleft = 0  + bleft;
				}else
				//a destra
				if(overright())
				{
					if($.browser.msie)
					{
					lensleft = smallimagedata.w - lensdata.w  + bleft + 1  ;
					}else
					{
					lensleft = smallimagedata.w - lensdata.w  + bleft - 1  ;
					}


				}

				//in alto
				if(overtop())
				{
					lenstop = 0 + btop ;
				}else
				//sotto
				if(overbottom())
				{

					if($.browser.msie)
					{
					lenstop = smallimagedata.h - lensdata.h  + btop + 1 ;
					}else
					{
					lenstop = smallimagedata.h - lensdata.h - 1 + btop  ;
					}

				}
				lensleft = parseInt(lensleft);
				lenstop = parseInt(lenstop);

				//setto lo zoom ed un eventuale immagine al centro
				$('div.jqZoomPup',a).css({top: lenstop,left: lensleft });

				if(settings.zoomType == 'reverse')
				{
					$('div.jqZoomPup img',a).css({'position': 'absolute','top': -( lenstop - btop +1) ,'left': -(lensleft - bleft +1)  });
				}

				this.node.style.left = lensleft + 'px';
				this.node.style.top = lenstop + 'px';

				//setto l'immagine grande
				largeimage.setposition();

				function overleft() {
					return mousepos.x - (lensdata.w +2*1)/2  - bleft < smallimagedata.pos.l;
				}

				function overright() {

					return mousepos.x + (lensdata.w + 2* 1)/2  > smallimagedata.pos.r + bleft ;
				}

				function overtop() {
					return mousepos.y - (lensdata.h + 2* 1)/2  - btop < smallimagedata.pos.t;
				}

				function overbottom() {
					return mousepos.y + (lensdata.h + 2* 1)/2    > smallimagedata.pos.b + btop;
				}

			return this;
		};


		//mostra la lente al centro dell'immagine
		Lens.prototype.center = function()
		{
			$('div.jqZoomPup',a).css('display','none');
			var lensleft = (smallimagedata.w)/2 - (lensdata.w)/2 ;
			var lenstop = (smallimagedata.h)/2 - (lensdata.h)/2;
			this.node.style.left = lensleft + 'px';
			this.node.style.top = lenstop + 'px';
			$('div.jqZoomPup',a).css({top: lenstop,left: lensleft });

			if(settings.zoomType == 'reverse')
			{
				/*if($.browser.safari){
					alert('safari');
					alert(2*bleft);
					$('div.jqZoomPup img',a).css({'position': 'absolute','top': -( lenstop - btop +1) ,'left': -(lensleft - 2*bleft)  });
				}else
				{*/
					$('div.jqZoomPup img',a).css({'position': 'absolute','top': -(lenstop - btop + 1) ,'left': -( lensleft  - bleft +1)   });
				//}
			}

			largeimage.setposition();
			if($.browser.msie)
			{
				$('div.jqZoomPup',a).show();
			}else
			{
				setTimeout(function(){$('div.jqZoomPup').fadeIn('fast');},10);
			}
		};


		//ritorna l'offset
		Lens.prototype.getoffset = function() {
			var o = {};
			o.left = parseInt(this.node.style.left) ;
			o.top =  parseInt(this.node.style.top) ;
			return o;
		};

		//rimuove la lente
		Lens.prototype.remove = function()
		{

			if(settings.zoomType == 'innerzoom')
			{
				$('div.jqZoomPup',a).fadeOut('fast',function(){/*$('div.jqZoomPup img').remove();*/$(this).remove();});
			}else
			{
				//$('div.jqZoomPup img').remove();
				$('div.jqZoomPup',a).remove();
			}
		};

		Lens.prototype.findborder = function()
		{
			var bordertop = '';
			bordertop = $('div.jqZoomPup').css('borderTop');
			//alert(bordertop);
			lensbtop = '';
			var borderleft = '';
			borderleft = $('div.jqZoomPup').css('borderLeft');
			lensbleft = '';
			if($.browser.msie)
			{
				var temp = bordertop.split(' ');

				bordertop = temp[1];
				var temp = borderleft.split(' ');
				borderleft = temp[1];
			}

			if(bordertop)
			{
				for(i=0;i<3;i++)
				{
					var x = [];
					x = bordertop.substr(i,1);

					if(isNaN(x) == false)
					{
						lensbtop = lensbtop +''+ bordertop.substr(i,1);
					}else
					{
						break;
					}
				}
			}

			if(borderleft)
			{
				for(i=0;i<3;i++)
				{
					if(!isNaN(borderleft.substr(i,1)))
					{
						lensbleft = lensbleft + borderleft.substr(i,1)
					}else
					{
						break;
					}
				}
			}


			lensbtop = (lensbtop.length > 0) ? eval(lensbtop) : 0;
			lensbleft = (lensbleft.length > 0) ? eval(lensbleft) : 0;
		}

		//LARGEIMAGE
		function Largeimage( url )
		{
			this.url = url;
			this.node = new Image();

			/*if(settings.preloadImages)
			{
			 	preload.push(new Image());
				preload.slice(-1).src = url ;
			}*/

			this.loadimage = function()
			{


				if(!this.node)
				this.node = new Image();

				this.node.style.position = 'absolute';
				this.node.style.display = 'none';
				this.node.style.left = '-5000px';
				this.node.style.top = '10px';
				loader = new Loader();

				if(settings.showPreload && !preloadshow)
				{
					loader.show();
					preloadshow = true;
				}

				document.body.appendChild( this.node );
				this.node.src = this.url; // fires off async
			}

			this.node.onload = function()
			{
				this.style.display = 'block';
				var w = Math.round($(this).width());
				var	h = Math.round($(this).height());

				this.style.display = 'none';

				//setting scale
				scale.x = (w / smallimagedata.w);
				scale.y = (h / smallimagedata.h);





				if($('div.preload').length > 0)
				{
					$('div.preload').remove();
				}

				largeimageloaded = true;

				if(settings.zoomType != 'innerzoom' && running){
					stage = new Stage();
					stage.activate();
				}

				if(running)
				{
				//alert('in');
				lens = new Lens();

				lens.activate() ;

				}
				//la attivo

				if($('div.preload').length > 0)
				{
					$('div.preload').remove();
				}
			}
			return this;
		}


		Largeimage.prototype.setposition = function()
		{
          	this.node.style.left = Math.ceil( - scale.x * parseInt(lens.getoffset().left) + bleft) + 'px';
			this.node.style.top = Math.ceil( - scale.y * parseInt(lens.getoffset().top) +btop) + 'px';
		};

		//setto la posizione dell'immagine grande nel caso di innerzoom
		Largeimage.prototype.setinner = function(e) {
          	this.node.style.left = Math.ceil( - scale.x * Math.abs(e.pageX - smallimagedata.pos.l)) + 'px';
			this.node.style.top = Math.ceil( - scale.y * Math.abs(e.pageY - smallimagedata.pos.t)) + 'px';
			$('div.jqZoomPup img',a).css({'position': 'absolute','top': this.node.style.top,'left': this.node.style.left  });
		};


		Largeimage.prototype.setcenter = function() {
          	this.node.style.left = Math.ceil(- scale.x * Math.abs((smallimagedata.w)/2)) + 'px';
			this.node.style.top = Math.ceil( - scale.y * Math.abs((smallimagedata.h)/2)) + 'px';


			$('div.jqZoomPup img',a).css({'position': 'absolute','top': this.node.style.top,'left': this.node.style.left  });
		};


		//STAGE
		function Stage()
		{

			var leftpos = smallimagedata.pos.l;
			var toppos = smallimagedata.pos.t;
			//creating element and class
			this.node = document.createElement("div");
			$(this.node).addClass('jqZoomWindow');

			$( this.node )
				.css({
					position: 'absolute',
					width: Math.round(settings.zoomWidth) + 'px',
					height: Math.round(settings.zoomHeight) + 'px',
					display: 'none',
					zIndex: 10000,
					overflow: 'hidden'
				});

			//fa il positionamento
		    switch(settings.position)
		    {
		    	case "right":

				leftpos = (smallimagedata.pos.r + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width)
				? (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset))
				: (smallimagedata.pos.l - settings.zoomWidth - Math.abs(settings.xOffset));

				topwindow = smallimagedata.pos.t + settings.yOffset + settings.zoomHeight;
				toppos = (topwindow < screen.height && topwindow > 0)
				?  smallimagedata.pos.t + settings.yOffset
				:  smallimagedata.pos.t;

		    	break;
		    	case "left":

				leftpos = (smallimagedata.pos.l - Math.abs(settings.xOffset) - settings.zoomWidth > 0)
				? (smallimagedata.pos.l - Math.abs(settings.xOffset) - settings.zoomWidth)
				: (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset));

				topwindow = smallimagedata.pos.t + settings.yOffset + settings.zoomHeight;
				toppos = (topwindow < screen.height && topwindow > 0)
				?  smallimagedata.pos.t + settings.yOffset
				:  smallimagedata.pos.t;

		    	break;
		    	case "top":

				toppos = (smallimagedata.pos.t - Math.abs(settings.yOffset) - settings.zoomHeight > 0)
				? (smallimagedata.pos.t - Math.abs(settings.yOffset) - settings.zoomHeight)
				: (smallimagedata.pos.t + smallimagedata.h + Math.abs(settings.yOffset));


				leftwindow = smallimagedata.pos.l + settings.xOffset + settings.zoomWidth;
				leftpos = (leftwindow < screen.width && leftwindow > 0)
				? smallimagedata.pos.l + settings.xOffset
				: smallimagedata.pos.l;

		    	break;
		    	case "bottom":


				toppos = (smallimagedata.pos.b + Math.abs(settings.yOffset) + settings.zoomHeight < $('body').height())
				? (smallimagedata.pos.b + Math.abs(settings.yOffset))
				: (smallimagedata.pos.t - settings.zoomHeight - Math.abs(settings.yOffset));


				leftwindow = smallimagedata.pos.l + settings.xOffset + settings.zoomWidth;
				leftpos = (leftwindow < screen.width && leftwindow > 0)
				? smallimagedata.pos.l + settings.xOffset
				: smallimagedata.pos.l;

		    	break;
		    	default:

				leftpos = (smallimagedata.pos.l + smallimagedata.w + settings.xOffset + settings.zoomWidth < screen.width)
				? (smallimagedata.pos.l + smallimagedata.w + Math.abs(settings.xOffset))
				: (smallimagedata.pos.l - settings.zoomWidth - Math.abs(settings.xOffset));

				toppos = (smallimagedata.pos.b + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height)
				? (smallimagedata.pos.b + Math.abs(settings.yOffset))
				: (smallimagedata.pos.t - settings.zoomHeight - Math.abs(settings.yOffset));

		    	break;
		    }

			this.node.style.left = leftpos + 'px';
			this.node.style.top = toppos + 'px';
			return this;
		}


		Stage.prototype.activate = function()
		{

			if ( !this.node.firstChild )
					this.node.appendChild( largeimage.node );


			if(settings.title)
			{
				ZoomTitleObj.loadtitle();
			}



			document.body.appendChild( this.node );


			switch(settings.showEffect)
			{
				case 'show':
					$(this.node).show();
				break;
				case 'fadein':
					$(this.node).fadeIn(settings.fadeinSpeed);
				break;
				default:
					$(this.node).show();
				break;
			}

			$(this.node).show();

            if ($.browser.msie && $.browser.version < 7) {
	        this.ieframe = $('<iframe class="zoom_ieframe" frameborder="0" src="#"></iframe>')
	          .css({ position: "absolute", left:this.node.style.left,top:this.node.style.top,zIndex: 99,width:settings.zoomWidth,height:settings.zoomHeight })
	          .insertBefore(this.node);
	     	 };


			largeimage.node.style.display = 'block';
		}

		Stage.prototype.remove = function() {
			switch(settings.hideEffect)
			{
				case 'hide':
					$('.jqZoomWindow').remove();
				break;
				case 'fadeout':
					$('.jqZoomWindow').fadeOut(settings.fadeoutSpeed);
				break;
				default:
					$('.jqZoomWindow').remove();
				break;
			}
		}

		function zoomTitle()
		{

			this.node =  jQuery('<div />')
				.addClass('jqZoomTitle')
				.html('' + ZoomTitle +'');

			this.loadtitle = function()
			{
				if(settings.zoomType == 'innerzoom')
				{
					$(this.node)
					.css({position: 'absolute',
						  top: smallimagedata.pos.b +3,
						  left: (smallimagedata.pos.l+1),
						  width:smallimagedata.w
						  })
					.appendTo('body');
				}else
				{
					$(this.node).appendTo(stage.node);
				}
			};
		}

		zoomTitle.prototype.remove = function() {
			$('.jqZoomTitle').remove();
		}


		function Loader()
		{

			this.node = document.createElement("div");
			$(this.node).addClass('preload');
			$(this.node).html(settings.preloadText);//appendo il testo

			$(this.node )
				.appendTo("body")
				.css('visibility','hidden');



			this.show = function()
			{
				switch(settings.preloadPosition)
				{
					case 'center':
						loadertop =  smallimagedata.pos.t + (smallimagedata.h - $(this.node ).height())/2;
						loaderleft = smallimagedata.pos.l + (smallimagedata.w - $(this.node ).width())/2;
					break;
					default:
					var loaderoffset = this.getoffset();
					loadertop = !isNaN(loaderoffset.top) ? smallimagedata.pos.t + loaderoffset.top : smallimagedata.pos.t + 0;
					loaderleft = !isNaN(loaderoffset.left) ? smallimagedata.pos.l + loaderoffset.left : smallimagedata.pos.l + 0;
					break;
				}

				//setting position
				$(this.node).css({
							top: loadertop  ,
							left: loaderleft ,
							position: 'absolute',
							visibility:'visible'
					    	});
			}
			return this;
		}

		Loader.prototype.getoffset = function()
		{
			var o = null;
			o = $('div.preload').offset();
			return o;
		}

		});
	}
})(jQuery);

	function trim(stringa)
	{
	    while (stringa.substring(0,1) == ' '){
	        stringa = stringa.substring(1, stringa.length);
	    }
	    while (stringa.substring(stringa.length-1, stringa.length) == ' '){
	        stringa = stringa.substring(0,stringa.length-1);
	    }
	    return stringa;
	}

/*>>>>>>>>>> jquery.ui.spinner.js <<<<<<<<<<*/
/*
 * jQuery UI Spinner @VERSION
 *
 * Copyright (c) 2008 jQuery
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Spinner
 *
 * Depends:
 *  ui.core.js
 */
(function($) {

$.widget('ui.spinner', {
	_init: function() {
		this._trigger('init', null, this.ui(null));
		
		// perform data bind on generic objects
		if (typeof this.options.items[0] == 'object' && !this.element.is('input')) {
			var data = this.options.items;
			for (var i=0; i<data.length; i++) {
				this._addItem(data[i]);
			}
		}
		
		// Setup the internal roundType (valid values = normal,roundUp)
		this._roundType = this.options.roundType;
		if(this._roundType != 'normal' && this._roundType != 'roundUp')
			this._roundType = 'normal';
		
		// check for decimals in steppinng and set _decimals as internal
		this._decimals = parseInt(this.options.decimals, 10);
		if (this.options.stepping.toString().indexOf('.') != -1) {
			var s = this.options.stepping.toString();
			this._decimals = s.slice(s.indexOf('.')+1, s.length).length;
		}
		
		//Initialize needed constants
		var self = this;
		this.element
			.addClass('ui-spinner-box')
			.attr('autocomplete', 'off'); // switch off autocomplete in opera
		
		this._setValue( isNaN(this._getValue()) ? this.options.start : this._getValue() );
		
		this.element
		.wrap('<div>')
		.parent()
			.addClass('ui-spinner')
			.append('<button class="ui-spinner-up" type="button">&#9650;</button>')
			.find('.ui-spinner-up')
				.bind('mousedown', function(e) {
					$(this).addClass('ui-spinner-pressed');
					if (!self.counter) {
						self.counter = 1;
					}
					self._mousedown(100, '_up', e);
				})
				.bind('mouseup', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					if (self.counter == 1) {
						self._up(e);
					}
					self._mouseup(e);
				})
				.bind('mouseout', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					if (self.timer) {
						self._mouseup(e);
					}
				})
				// mousedown/mouseup capture first click, now handle second click
				.bind('dblclick', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					self._up(e);
					self._mouseup(e);
				})
				.bind('keydown.spinner', function(e) {
					var KEYS = $.ui.keyCode;
					var keyId = e.keyCode ? e.keyCode : e.which;
					if (keyId == KEYS.SPACE || keyId == KEYS.ENTER) {
						$(this).addClass('ui-spinner-pressed');
						if (!self.counter) {
							self.counter = 1;
						}
						self._up.call(self, e);
					} else if (keyId == KEYS.DOWN || keyId == KEYS.RIGHT) {
						self.element.siblings('.ui-spinner-down').focus();
					} else if (keyId == KEYS.LEFT) {
						self.element.focus();
					}
				})
				.bind('keyup.spinner', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					self.counter = 0;
					self._propagate('change', e);
				})
			.end()
			.append('<button class="ui-spinner-down" type="button">&#9660;</button>')
			.find('.ui-spinner-down')
				.bind('mousedown', function(e) {
					$(this).addClass('ui-spinner-pressed');
					if (!self.counter) {
						self.counter = 1;
					}
					self._mousedown(100, '_down', e);
				})
				.bind('mouseup', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					if (self.counter == 1) {
						self._down();
					}
					self._mouseup(e);
				})
				.bind('mouseout', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					if (self.timer) {
						self._mouseup(e);
					}
				})
				// mousedown/mouseup capture first click, now handle second click
				.bind('dblclick', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					self._down(e);
					self._mouseup(e);
				})
				.bind('keydown.spinner', function(e) {
					var KEYS = $.ui.keyCode;
					var keyId = e.keyCode ? e.keyCode : e.which;
					if (keyId == KEYS.SPACE || keyId == KEYS.ENTER) {
						$(this).addClass('ui-spinner-pressed');
						if (!self.counter) {
							self.counter = 1;
						}
						self._down.call(self, e);
					} else if (keyId == KEYS.UP || keyId == KEYS.LEFT) {
						self.element.siblings('.ui-spinner-up').focus();
					}
				})
				.bind('keyup.spinner', function(e) {
					$(this).removeClass('ui-spinner-pressed');
					self.counter = 0;
					self._propagate('change', e);
				})
			.end();
		
		// DataList: Set contraints for object length and step size. 
		// Manipulate height of spinner.
		this._items = this.element.children().length;
		if (this._items > 1) {
			var height = this.element.outerHeight()/this._items;
			this.element
			.addClass('ui-spinner-list')
			.height(height)
			.children()
				.addClass('ui-spinner-listitem')
				.height(height)
				.css('overflow', 'hidden')
			.end()
			.parent()
				.height(height)
			.end();
			this.options.stepping = 1;
			this.options.min = 0;
			this.options.max = this._items-1;
		}
		
		this.element
		.bind('keydown.spinner', function(e) {
			if (!self.counter) {
				self.counter = 1;
			}
			return self._keydown.call(self, e);
		})
		.bind('keyup.spinner', function(e) {
			self.counter = 0;
			self._propagate('change', e);
		})
		.bind('blur.spinner', function(e) {
			if( self._roundType == 'roundUp' ) {
				self._roundUp();
			}
			self._cleanUp();
			
		});
		
		if ($.fn.mousewheel) {
			this.element.mousewheel(function(e, delta) {
				self._mousewheel(e, delta);
			});
		}
	},
	_constrain: function() {
		if (this.options.min != undefined && this._getValue() < this.options.min) {
			this._setValue(this.options.min);
		}
		if (this.options.max != undefined && this._getValue() > this.options.max) {
			this._setValue(this.options.max);
		}
	},
	_roundUp: function() {
		if( this._getValue() % this.options.stepping != 0 ) {
			this._setValue( (parseInt( this._getValue() / this.options.stepping ) * this.options.stepping) + this.options.stepping );
		}
	},
	_cleanUp: function() {
		this._setValue(this._getValue());
		this._constrain();
	},
	_spin: function(d, e) {
		if (this.disabled) {
			return;
		}
		
		if (isNaN(this._getValue())) {
			this._setValue(this.options.start);
		}
		this._setValue(this._getValue() + (d == 'up' ? 1:-1) * (this.options.incremental && this.counter > 100 ? (this.counter > 200 ? 100 : 10) : 1) * this.options.stepping);
		this._animate(d);
		this._constrain();
		if (this.counter) {
			this.counter++;
		}
		this._propagate('spin', e);
	},
	_down: function(e) {
		this._spin('down', e);
		this._propagate('down', e);
	},
	_up: function(e) {
		this._spin('up', e);
		this._propagate('up', e);
	},
	_mousedown: function(i, d, e) {
		var self = this;
		i = i || 100;
		if (this.timer) {
			window.clearInterval(this.timer);
			this.timer = 0;
		}
		this.timer = window.setInterval(function() {
			self[d](e);
			if (self.counter > 20) {
				self._mousedown(20, d, e);
			}
		}, i);
	},
	_mouseup: function(e) {
		this.counter = 0;
		if (this.timer) {
			window.clearInterval(this.timer);
			this.timer = 0;
		}
		this.element[0].focus();
		this._propagate('change', e);
	},
	_keydown: function(e) {
		var KEYS = $.ui.keyCode;
		var keyId = e.keyCode ? e.keyCode : e.which;
		if (keyId == KEYS.UP) {
			this._up(e);
		}
		if (keyId == KEYS.DOWN) {
			this._down(e);
		}
		if (keyId == KEYS.HOME) {
			//Home key goes to min, if defined, else to start
			this._setValue(this.options.min || this.options.start);
		}
		if (keyId == KEYS.END && this.options.max != undefined) {
			//End key goes to maximum
			this._setValue(this.options.max);
		}
		return (keyId == KEYS.TAB || keyId == KEYS.BACKSPACE ||
				keyId == KEYS.LEFT || keyId == KEYS.RIGHT || keyId == KEYS.PERIOD || 
				keyId == KEYS.NUMPAD_DECIMAL || keyId == KEYS.NUMPAD_SUBTRACT || 
			(keyId >= 96 && keyId <= 105) || // add support for numeric keypad 0-9
			(/[0-9\-\.]/).test(String.fromCharCode(keyId))) ? true : false;
	},
	_mousewheel: function(e, delta) {
		var self = this;
		delta = ($.browser.opera ? -delta / Math.abs(delta) : delta);
		(delta > 0 ? self._up(e) : self._down(e));
		if (self.timeout) {
			window.clearTimeout(self.timeout);
			self.timeout = 0;
		}
		self.timeout = window.setTimeout(function(){self._propagate('change', e)}, 400);
		e.preventDefault();
	},
	_getValue: function() {
		return parseFloat(this.element.val().replace(/[^0-9\-\.]/g, ''));
	},
	_setValue: function(newVal) {
		if (isNaN(newVal)) {
			newVal = this.options.start;
		}
		this.element.val(
			this.options.currency ? 
				$.ui.spinner.format.currency(newVal, this.options.currency) : 
				$.ui.spinner.format.number(newVal, this._decimals)
		);
	},
	_animate: function(d) {
		if (this.element.hasClass('ui-spinner-list') && ((d == 'up' && this._getValue() <= this.options.max) || (d == 'down' && this._getValue() >= this.options.min)) ) {
			this.element.animate({marginTop: '-' + this._getValue() * this.element.parent().height() }, {
				duration: 'fast',
				queue: false
			});
		}
	},
	_addItem: function(obj, fmt) {
		if (!this.element.is('input')) {
			var wrapper = 'div';
			if (this.element.is('ol') || this.element.is('ul')) {
				wrapper = 'li';
			}
			var html = obj; // string or object set it to html first
			
			if (typeof obj == 'object') {
				var format = (fmt !== undefined ? fmt : this.options.format);
				
				html = format.replace(/%(\(([^)]+)\))?/g, 
					(function(data){
						return function(match, a, lbl) { 
							if (!lbl) {
								for (var itm in data) {
									return data[itm]; // return the first item only
								}
							} else {
								return data[lbl];
							}
						};
					})(obj)
				);
			}
			this.element.append('<'+ wrapper +' class="ui-spinner-dyn">'+ html + '</'+ wrapper +'>');
		}
	},
	
	plugins: {},
	ui: function(e) {
		return {
			options: this.options,
			element: this.element,
			value: this._getValue(),
			add: this._addItem
		};
	},
	_propagate: function(n,e) {
		$.ui.plugin.call(this, n, [e, this.ui()]);
		return this.element.triggerHandler(n == 'spin' ? n : 'spin'+n, [e, this.ui()], this.options[n]);
	},
	destroy: function() {
		if (!$.data(this.element[0], 'spinner')) {
			return;
		}
		if ($.fn.mousewheel) {
			this.element.unmousewheel();
		}
		this.element
			.removeClass('ui-spinner-box ui-spinner-list')
			.removeAttr('disabled')
			.removeAttr('autocomplete')
			.removeData('spinner')
			.unbind('.spinner')
			.siblings()
				.remove()
			.end()
			.children()
				.removeClass('ui-spinner-listitem')
				.remove('.ui-spinner-dyn')
			.end()
			.parent()
				.removeClass('ui-spinner ui-spinner-disabled')
				.before(this.element.clone())
				.remove()
			.end();
	},
	enable: function() {
		this.element
			.removeAttr('disabled')
			.siblings()
				.removeAttr('disabled')
			.parent()
				.removeClass('ui-spinner-disabled');
		this.disabled = false;
	},
	disable: function() {
		this.element
			.attr('disabled', true)
			.siblings()
				.attr('disabled', true)
			.parent()
				.addClass('ui-spinner-disabled');
		this.disabled = true;
	}
});

$.extend($.ui.spinner, {
	defaults: {
		decimals: 0,
		stepping: 1,
		start: 0,
		incremental: true,
		currency: false,
		format: '%',
		roundType: 'normal', // Valid options: normal, roundUp (ie: input: 8.1 -> 8.5 if _this.decimals > 0, else -> 9) 
		items: []
	},
	format: {
		currency: function(num, sym) {
			num = isNaN(num) ? 0 : num;
			return (num !== Math.abs(num) ? '-' : '') + sym + this.number(Math.abs(num), 2);
		},
		number: function(num, dec) {
			var regex = /(\d+)(\d{3})/;
			for (num = isNaN(num) ? 0 : parseFloat(num,10).toFixed(dec); regex.test(num); num=num.replace(regex, '$1,$2'));
			return num;
		}
		
	}
});

})(jQuery);



/*>>>>>>>>>> shoppingCart.js <<<<<<<<<<*/
/*****************************************************************
 * Name: shoppingCart.js
 * 
 * PLEASE KEEP THE FUNCTIONS IN ALPHABETICAL ORDER. 
 * 
 * PLEASE DON'T ADD HARDCODED TEXT INSIDE THIS FILE, IT TOOK A WHILE TO CLEAN UP!
 * 
 * THANKS YOU!
 *
 */

function getPaymentMethodSelected() {
	var oPaymentMethodID = "";
	
	if (j$("select##radioPayment").length) {
		oPaymentMethodID = j$("select##radioPayment option:selected").attr("id");
	} else if (j$("input[name='radioPayment']:hidden").length) {
			oPaymentMethodID = j$("input[name='radioPayment']:hidden").attr("id");
	} else if (j$("input:radio[name='radioPayment']:checked").length) {
		oPaymentMethodID = j$("input:radio[name='radioPayment']:checked").attr("id");
	}
	return oPaymentMethodID;
}


function addPersonalisation_ajax () {
	
	var jDialog = j$( "#personalisationQuantitySelector" );
	
	var args = {
			method: "addPersonalisation_getIFrameLink"
		,	orderID: j$( "#dialog_personalisation_order_id" ).val()
		,	quantity: j$( "#dialog_personalisation_quantity").val()
		,	sku_id: j$( "#dialog_personalisation_sku_id").val()
		,	line_item_no: j$( "#dialog_personalisation_line_item_no").val()
		,	source: j$( "#dialog_personalisation_source").val()
		,	need_approval: j$( "#dialog_personalisation_need_approval").val()
	}
	
	j$.post(
			siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
		,	args
		,	addPersonalisation_ajax_result
		,	"json"
	);
	
}

function addPersonalisation_ajax_result ( result ) {
	
	j$( "#personalisationQuantitySelector" ).dialog( "close" );
	
	if ( ! result.SUCCESS ) {
	
		var warningContent;
		
		switch ( result.ERROR ) {
			case "VISION_TIMEOUT_ERROR":
				warningContent = msg_visionTimeoutError;
				break;
			case "VISION_CONNECTION_ERROR":
				warningContent = msg_visionConnectionError;
				break;
			case "VISION_GENERAL_ERROR":
				warningContent = msg_visionGeneralError;
				break;
		}
		
		warningContent = "<div>" + warningContent + "</div>";
		
		j$( warningContent ).dialog({
				autoOpen: true
		});
		
		return false;
	}
	
	var iFrameContent = "<div><iframe id='testpersonalisation' src=\"" + result.IFRAMELINK + "\" width='760' height='515' marginwidth='0' marginheight='0'></iframe></div>";
	
	j$( iFrameContent ).dialog({ 
			autoOpen: true
		,	width: 800
		,	height: "auto"
		,	modal: true
	});
	
}

function addPersonalisation_selectQuantity ( sku_id, line_item_no, quantity, order_id ) {
	var jDialog = j$( "#personalisationQuantitySelector" );
	g_INITIAL_PERSONALISATION_QUANTITY_DIALOG_CONTENTS = jDialog.html();
		
	jDialog.html( jDialog.html().replace( /::[^:]+::/g, "" ) );
		
	jDialog.dialog( "open" );
	jDialog.find( "input[name=dialog_personalisation_sku_id]" ).val( sku_id );
	jDialog.find( "input[name=dialog_personalisation_line_item_no]" ).val( line_item_no );
	jDialog.find( "input[name=dialog_personalisation_quantity]" ).val( quantity );
	
	if ( order_id )
		jDialog.find( "input[name=dialog_personalisation_order_id]" ).val( order_id );
	
	return false;
}

function addPrize_ajax () {
	var jDialog = j$( "#prizeQuantitySelector" );
	var args = {
			method: "addPrizeItem"
		,	orderID: j$( "#dialog_prize_order_id").val()
		,	quantity: j$( "#dialog_prize_quantity").val()
		,	sku_id: j$( "#dialog_prize_sku_id").val()
		,	line_item_no: j$( "#dialog_prize_line_item_no").val()
		,	personalisation_GUID: j$( "#dialog_prize_personalisation_GUID").val()
	}
	
	j$.post(
			siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
		,	args
		,	addPrize_ajax_result
		,	"json"
	);	
}

function addPrize_ajax_result ( result ) {
	j$( "#prizeQuantitySelector" ).dialog( "close" );
	if ( ! result.SUCCESS ) {
		var warningContent = "<div>" + msg_visionGeneralError + "</div>";
		j$( warningContent ).dialog({ autoOpen: true });		
		return false;
	}
	location.href = location.href;
}

function addPrize_selectQuantity ( order_id, sku_id, line_item_no, guid ) {
	var jDialog = j$( "#prizeQuantitySelector" );
	g_INITIAL_PRIZE_QUANTITY_DIALOG_CONTENTS = jDialog.html();

	jDialog.find( ":input[ name=dialog_prize_order_id ]" ).val( order_id );
	jDialog.find( ":input[ name=dialog_prize_sku_id ]" ).val( sku_id );
	jDialog.find( ":input[ name=dialog_prize_line_item_no ]" ).val( line_item_no );
	jDialog.find( ":input[ name=dialog_prize_personalisation_GUID ]" ).val( guid );

	jDialog.dialog( "open" );
	return false;
}

function setLotNumber_ajax (rowId) {
	var args = {
			method: "setLotNumber"
		,	orderID: j$( "#orderID" ).val()
		,	lotNumber: j$("#LotNumber_" + rowId).val()
		,	line_item_no: j$( "#line_item_no_" + rowId).val()
	}

	j$.post(
			siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
		,	args
		,	function(result) { return false; }
		,	"json"
	);
}

function addUpdateGiftwrap_Result(result){
	
	window.location.href = g_linkUpdateCartServlet;
	showAlert({message:msg_giftWrapAdded ,closeBText:'x',cssClass:'alertboxSmall'});	
}

function blockShowOtherSteps ()
{
	canshowothersteps = 'N';
}
		
function setPaymentMethod() {
	var oPaymentMethod = j$("select#radioPayment");
	var oPaymentMethodID = getPaymentMethodSelected();
	j$("div[id^='paymentMethod_']").hide();
	if (oPaymentMethodID == 'radioPaymentCC') { j$("div#paymentMethod_CreditCard").show();
	} else if (oPaymentMethodID == 'radioPaymentPaypal') { j$("div#paymentMethod_PayPal").show();
	} else if (oPaymentMethodID == 'radioPaymentInterac') { j$("div#paymentMethod_Interac").show();
	} else if (oPaymentMethodID == 'radioPaymentPO') { j$("div#paymentMethod_PO").show();
	} else if (oPaymentMethodID == 'radioPaymentSampleAccount') { j$("div#paymentMethod_SampleAccount").show();
	}
	checkCreditCard(false);
}

function checkCreditCard(refreshPage)
{
	g_refresh_page = refreshPage;
	var oCCSelected = false;
	if (getPaymentMethodSelected() == 'radioPaymentCC') {
		cardSelected = $('cardType').value;
	} else { 
		cardSelected = '';
		if ( $('promotiondiscounttax') ) 
			$('promotiondiscounttax').style.display = 'none';
	}

	DWREngine._execute(_cfPaymentsFunctions, null,'setPaymentMethod',cardSelected,dummy_Result);
}

function checkDiscount(refreshPage, isFreeShipping)
{
	
	hideButton(true);
	
	g_numberLineItems = j$("#skuCount").val(); 
	
 	g_refreshPage = refreshPage;

 	if($('Discounts')){
 		discountcode = $('Discounts').value;
 	} else {
 		discountcode = '';
 	}	
 	
	DWREngine._execute(_cfPaymentsFunctions, null,'callapplyDiscountCode',discountcode,g_ukey,checkDiscount_Result);	
}
 
function checkDiscount_Result(result)
{


	var discountHaveFreeItem = false;
	
 	discountResult = result.split("~");
		 	
 	if(discountResult[0]=='invalid')
 	{	
 		//Discount is not valid
 		j$("#discountShow").hide();
 		j$("#discountAmount").html('');
 		
 		temp = discountResult[2].replace('$','');
 		j$("#totalPrice").html('$'+temp);
	    
	    if(g_refreshPage == true){
		    //Refresh the page
		    if(g_currentShoppingCartPage == "shoppingCartPayment")
	 			refreshPaymentPage("discountNotValid");
	 		else
	 			refreshShoppingCartPage("discountNotValid");
	    } else {
	    	j$("#Discounts").val('');
	    	hideButton(false);
	    }
 	} else {
		
 		//Discount is valid
		//g_refreshPage = true;
 		if(g_refreshPage == true){
 			//Refresh the page
 			if(g_currentShoppingCartPage == "shoppingCartPayment")
 				refreshPaymentPage("");
 			else
 				refreshShoppingCartPage("");
 		}else{
		 	if (discountResult[0]=='valid') {
	        	//Discount type is free item
	        	if(discountResult[3]==5) {
	            	discountHaveFreeItem = true;
       				j$("#discountShow").hide();
		        	j$("#discountAmount").html( '' );
	 				temp = discountResult[2].replace('$','');
			 		j$("#totalPrice").html('$'+temp);
	        		DWREngine._execute(_cfPaymentsFunctions, null,'callfreeItemDiscount',g_actualLang,checkDiscountFreeItemdiscount_Result);
	            } else {
	        		//Free item indicator 
	        		if(discountResult[7]=='Y') {
	        			discountHaveFreeItem = true;
        				DWREngine._execute(_cfPaymentsFunctions, null,'callfreeItemDiscount',g_actualLang,checkDiscountFreeItemdiscount_Result);
	        		}
	        		
       				j$("#discountShow").show();
		        	j$("#discountAmount").html( discountResult[1] );
		        	temp = discountResult[2].replace('$','') - discountResult[4].replace('$','') - discountResult[5].replace('$','');
			 		j$("#totalPrice").html('$'+temp.toFixed(2));
	        	}	
	        }
		 	//refreshShippingMethod();
			if($("ShopShippingMethod")){
				if ( j$("input[name=ShopShippingMethod]").attr('type') =='radio' ) {
					shippingMethodvalue = j$("input[name=ShopShippingMethod]:checked").val();
				} else {
					shippingMethodvalue = j$("#ShopShippingMethod").val();
				}
				UpdateShipping(shippingMethodvalue);
			} else if($("SHIPPINGMETHODID")){
				if ( j$("input[name=SHIPPINGMETHODID]").attr('type') =='radio' ) {
					shippingMethodvalue = j$("input[name=SHIPPINGMETHODID]:checked").val();
				} else {
					shippingMethodvalue = j$("#SHIPPINGMETHODID").val();
				}
				UpdateShipping(shippingMethodvalue);
			}			
 		}			 	
 	}
}

function addDiscountRow(itemNumber, amount)
{
	if(j$('#ThisRow_' + itemNumber))
	{
		// determine the colspan
		var arTableCells = j$('#ThisRow_' + itemNumber).children('td');
		var colSpan = arTableCells.length;
		
		if(j$('#DiscountRow_' + itemNumber).length)
		{
			// this item already has a discount row. Exit the function.
			return;
		}
		var row = j$('<tr id="DiscountRow_' + itemNumber + '"></tr>');
		var cell = j$('<td colspan="' + colSpan + '" class="lineItemDiscount"></td>');
		var labelSpan = j$('<span class="lineItemDiscountLabel">Discount:</span>');
		var amountSpan = j$('<span class="lineItemDiscountValue">' + amount + '</span>');
		
		// insert the two spans into the td
		j$(cell).append(labelSpan, amountSpan);
		
		// insert the td into the tr
		j$(row).append(cell);
		
		// insert this new row into the table, after the corresponding item row
		j$('#ThisRow_' + itemNumber).after(row);
	}
	
}

function checkDiscountFreeItemdiscount_Result(result)
{ 
	var positionDiscount = 0;
	
	freeItemResult = result.split("~");

 	showFreeItemSizeColorOnRefresh = false;

	//If the first field is 0 or 1 is 0, that mean there's no qty available
	if(freeItemResult[0] == 0 || freeItemResult[1] == 0 || freeItemResult[0] == 'Out of stock'){
		showAlert({message:msg_freeItemOutOfStock, cssClass:'', closeBText:msg_closeBox,cssClass:'alertboxSmall'});						
	}else if(freeItemResult[4] == 'N') {
		if (!g_splitOrder){
				
	 		//Put the select box of the free item to select a size...
	 		for(count = 1;count <= g_numberLineItems;count++){
				
	 			if($("freeFromDiscountCode_" + count) && $("freeFromDiscountCode_" + count).value == "Y"){
	 				
	 				positionDiscount = count;
	 				
			 		if($("skuID_" + count))
			 			$("skuID_" + count).selectedIndex = 0;
	
			 		if($("color_" + count))
			 			$("color_" + count).selectedIndex = 0;		 				
	 			}
	 		}
	 		
	 		if($("isSingleSku_" + positionDiscount) && $("isSingleSku_" + positionDiscount).value == 0){			 			
	 			//Popup to ask the customer to select size and color for free item	
				showAlert({message:msg_freeItemSizeColor,cssClass:'',closeBText:msg_closeBox,cssClass:'alertboxSmall'});
			}
		} else {
			if (typeof freeItemInfo != "undefined"){
				params = ["orderId=" + freeItemInfo.orderId,"lineItemNumber=" + freeItemInfo.lineItemNumber];
				j$("#freeItemSelection").load(g_linkfornewitempopup + "&" + params.join("&")).dialog("open");
			}
		}
 	}
}	
	
function checkExisting(skuID,currRow,itemDesc)
{
 	TotRow = $('skuCount').value;
 	Merge = false;

 	for(i=1;i<=TotRow;i++)
 	{
 		if(i != currRow)
 		{
 			RowSKU = $('skuID_'+i).value;
 			if(RowSKU == skuID)
 			{
 				//merge records
 				currRowQty = $('qty_'+currRow);
 				ModRowQty = $('qty_'+i);

 				ModRowQty.value = parseInt(currRowQty.value) + parseInt(ModRowQty.value);
 				currRowQty.value = 0;
 				
 				$('ThisRow_'+currRow).style.display = 'none';
 				
 				checkQty('qty_'+i,'currentQty_'+i,itemDesc,i);
 			
 				Merge = true;
 				break;
 			}
 		}
 	}

 	return Merge;
}
 			
function checkExportCountryeachItem(shippingCountryID){
       	
 	if(shippingCountryID !=''){
       		DWREngine._execute(_cfPaymentsFunctions, null,'callCheckExportCountryeachItem',shippingCountryID,checkExportCountryeachItem_Result);
       	}
      }
       
function checkExportCountryeachItem_Result(result){
 	if(result!=''){
 	   window.location.reload();
 	}
}
       
function checkFreeItemPromotionSelect(promoFreeItemPopupId,numberRecord){
	
	var positionPromotion = 0;
	
	if(promoFreeItemPopupId != ""){
	
 		//Put the select box of the free item to select a size...
 		for(count = 1;count <= numberRecord ;count++){

 			if($("freeFromPromotion_" + count) && $("freeFromPromotion_" + count).value == "Y"){
 				
 				positionPromotion = count;
 				
		 		if($("skuID_" + count))
		 			$("skuID_" + count).selectedIndex = 0;

		 		if($("color_" + count))
		 			$("color_" + count).selectedIndex = 0;		 				
 			}		 				
 		}
 		
 		if($("isSingleSku_" + positionPromotion) && $("isSingleSku_" + positionPromotion).value == 0){
 			//Popup to ask the customer to select size and color for free item	
			showAlert({message:msg_freeItemSizeColor,cssClass:'',closeBText:msg_closeBox,cssClass:'alertboxSmall'});
		}	 				
	}		
}	

function checkStarCard(cardNumber)
{

		DWREngine._execute(_cfPaymentsFunctions, null,'callvalidateStarCard',cardNumber,starCard_Result);
}

//result: error message if invalid star card; otherwise blank
function starCard_Result(result)
{
	
	starCardResult = result;
	dspErrorMsg = "";

 	if(result == "")
 	{	
 		if ($("starCardErrorMessage")) 
 		{
 			$("starCardErrorMessage").innerHTML = '';
 			$("starCardErrorMessage").style.display = "none";
 		}
 	}
 	else
 	{	
 		if ($("starCardErrorMessage")) 
 		{
 			starCardResult = result.split("~");
 			for (i=0;i<starCardResult.length;i++) 
 			{
 				dspErrorMsg += starCardResult[i];
 				if(starCardResult.length > 1) dspErrorMsg+= "<br>";
 			}
 			
 			$("starCardErrorMessage").innerHTML = dspErrorMsg; 
 			$("starCardErrorMessage").style.display = "block";
 		}
 	}
}


function checkGiftCard(ukey,egc,egcpin,egcamount,count)
{

		DWREngine._execute(_cfPaymentsFunctions, null,'callapplyGiftCard',ukey,egc,egcpin,egcamount,count,'#variables.actualLang#',checkGiftCard_Result);
}

function checkGiftCard_Result(result)
{

 	giftCardResult = result.split("~");

 	if(giftCardResult[0] =='true')
 	{	
 		if ($("errorGiftCard")) $("errorGiftCard").innerHTML = ''; 
       	if ($("giftcard")) $("giftcard").style.display ='';
       	if ($("giftcardAmount")) $("giftcardAmount").innerHTML = giftCardResult[1]; 
       	if ($("totalPrice"))  $("totalPrice").innerHTML = giftCardResult[2];
       	if ($("addGiftCardLink") && giftCardResult[7] < $("valMaximumGiftCards").value) $("addGiftCardLink").style.display = "block";
 	}
 	else
 	{
 		if (giftCardResult.length ==1)
 		{	
 			if ($("errorGiftCard")) $("errorGiftCard").innerHTML = ''; 
        	if ($("giftcard")) $("giftcard").style.display ='none';
        	if ($("giftcardAmount")) $("giftcardAmount").innerHTML = ''; 
        	if ($("totalPrice"))  $("totalPrice").innerHTML = giftCardResult[2];
        	if ($("addGiftCardLink")) $("addGiftCardLink").style.display = "none";
 		}
	 	else
	 	 {  
	 	 	if(giftCardResult[6] == 1)
	 	 	{
	 	 		if ($("giftcard")) $("giftcard").style.display ='none';
     		    if ($("giftcardAmount")) $("giftcardAmount").innerHTML = '';
	 	 		if ($("totalPrice")) $("totalPrice").innerHTML = giftCardResult[2];
	 	 		if ($("addGiftCardLink")) $("addGiftCardLink").style.display = "block";
	 	 	}
	 	 	else
	 	 	{	
		 	 	$("errorGiftCard").innerHTML = giftCardResult[1]; 
	 	 		if ($("addGiftCardLink")) $("addGiftCardLink").style.display = "none";
		 	 	if (giftCardResult[4] == "$0.00")
		 	 	{	
    		        	if ($("giftcard")) $("giftcard").style.display ='none';
    		        	if ($("giftcardAmount")) $("giftcardAmount").innerHTML = '';
    		      	}
    		      	else
    		      	{ 
     		         if ($("giftcard")) $("giftcard").style.display ='';
     		        if ($("giftcardAmount")) $("giftcardAmount").innerHTML = giftCardResult[2];
     		     }  	 
		        	if ($("totalPrice")) $("totalPrice").innerHTML = giftCardResult[3];
	 	 	}
		 }
 	}
}      
    			
function checkPrestigeCard(prestigecode)
{
	$('prestigeCheckInProgress').value = 'Y';
	DWREngine._execute(_cfPaymentsFunctions, null,'callapplyMembershipCardCode',prestigecode,g_ukey,checkPrestigeCard_Result);
}

function checkPrestigeCard_Result(result)
{

	prestigeResult = result.split("~");

	if (prestigeResult[0]=='valid')
    {
      	$("errorPrestige").innerHTML = ''; 
      	$("errorPrestige").style.display = 'none';
      	$("prestige").style.display ='';
      	$("prestigeAmount").innerHTML = prestigeResult[1]; 
      	if ($("totalPrice")) $("totalPrice").innerHTML = prestigeResult[2];
      	if($("tax1value")!=null) $("tax1value").innerHTML = prestigeResult[4];
       if($("tax2value")!=null) $("tax2value").innerHTML = prestigeResult[5];
    }
    
    if (prestigeResult[0]=='invalid' )
    {
      	$("prestige").style.display ='none';
		$("prestigeAmount").innerHTML = ''; 
		$("errorPrestige").style.display = ''; 
		$("errorPrestige").innerHTML = msg_errorPrestigeCard; 
		if ($("totalPrice")) $("totalPrice").innerHTML = prestigeResult[2];
		if($("tax1value")!=null) $("tax1value").innerHTML = prestigeResult[4];
        if($("tax2value")!=null) $("tax2value").innerHTML = prestigeResult[5];
	}
      
    if (prestigeResult[0]=='empty' )
    {
		$("prestige").style.display ='none';
		$("prestigeAmount").innerHTML = ''; 
		$("errorPrestige").innerHTML = ''; 
		$("errorPrestige").style.display = 'none';
		if ($("totalPrice")) $("totalPrice").innerHTML = prestigeResult[2];
		if($("tax1value")!=null) $("tax1value").innerHTML = prestigeResult[4];
        if($("tax2value")!=null) $("tax2value").innerHTML = prestigeResult[5];
    }
      
    //prestige length logic
    if (prestigeResult.length ==2)
    {
      	$("prestige").style.display ='none';
      	$("prestigeAmount").innerHTML = ''; 
      	$("errorPrestige").innerHTML = ''; 
      	$("errorPrestige").style.display = 'none';
      	if ($("totalPrice")) $("totalPrice").innerHTML = prestigeResult[0];
    }
      
    $('prestigeCheckInProgress').value = 'N';
}         			

function checkSelectGiftWrap(errorMSG,ukey,orderID,currencyID){
		
    if($('selectGiftWrapType').value == '') 
       alert(errorMSG);
    else {
     	CFID = g_cfid;
		CFTOKEN = g_cftoken;
	
		CFID_CFTOKEN = "";
		if(CFID.length > 0)
		{
			CFID_CFTOKEN = CFID+"_"+CFTOKEN;
		}
		oldGiftWrapsku=$('oldSelectGiftWrap').value;
		lineItemNO=$('lineitemNO').value;
		selectColorID=$('selectGiftWrapType').value;
		qty=1;
		oldGiftWrapLineNo=$('oldSelectGiftWrapLineNo').value;
      	
        DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'addUpdateGiftwrap','#session.actualLang#',CFID_CFTOKEN,selectColorID,qty,lineItemNO,oldGiftWrapsku,oldGiftWrapLineNo,ukey,orderID,currencyID, addUpdateGiftwrap_Result);
    }
}

function checkUpsRates()
{
 	hideButton(true);
 	zipcode = $('ZipCode').value;
 	DWREngine._execute(_cfPaymentsFunctions, null,'callapplyUpsRates',zipcode,g_ukey,checkUpsRates_Result);
 		
}
 
function checkUpsRates_Result(result)
{
 	hideButton(true);
 	
 	upsResult = result.split("~");
 	for (i=0; i<upsResult.length; i++) {
 		upsResultDetail = upsResult[i].split("|");
 		orderNumber = upsResultDetail[0];
 		if ($("ShopShippingMethod")){
			for (j=0;j< $("ShopShippingMethod").length;j++) 			
			{
				shippingMethodValue = $("ShopShippingMethod")[j].value;
				if(shippingMethodValue == upsResultDetail[1]) {
					shippingMethodDescription = $("ShopShippingMethod")[j].innerHTML.split("-");
					if (upsResultDetail[2] == "0") {
						$("ShopShippingMethod")[j].innerHTML = shippingMethodDescription[0] + msg_enterZipCode;
					} else {
						$("ShopShippingMethod")[j].innerHTML = shippingMethodDescription[0] + ' - ' + upsResultDetail[2];
					}	
				}
			}
			
			
			
		}	
	}
	
	if ($("ShopShippingMethod"))
	{
		shippingMethodID = $("ShopShippingMethod").options[$("ShopShippingMethod").selectedIndex].value;
			
		UpdateShipping(shippingMethodID);
	}
	else
	{
		hideButton(false);
	}
	
}
 		
function checkQty(ID,origQtyID,desc,row)
{
	QtyVal = $(ID).value;
	QtyTarget = ID;
	OrigVal = $(origQtyID).value;
	
	errDiv = $('error_qty_'+''+row);
	errDiv.style.display = 'none';
	
	skuIDD=eval($('skuID_'+''+row));
	skuID = skuIDD.value;
	
	if($('skuID_'+''+row))
	{
		sizeIDD=eval($('skuID_'+''+row));
		sizeIDD = sizeIDD.value;
	}
	else
	{
		sizeIDD = 'good';
	}
	
	if (OrigVal != QtyVal)
	{
	
		if (sizeIDD == '')
		{
			showAlert({message:msg_errorSize, closeBText:'x', cssClass:'alertboxSmall'});
			$(ID).value = OrigVal;
		}
		else if (QtyVal == '')
		{
			showAlert({message:msg_errorQty + desc,closeBText:'x',cssClass:'alertboxSmall'});
		}	
		else if(_isInteger(QtyVal))	
		{
								
			DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'CheckStyleAvailable',skuID,QtyVal,checkQty_Result);
		}
		else
		{
			showAlert({message:msg_errorNumberQty + " " + desc,closeBText:'x',cssClass:'alertboxSmall'});
		}
	}
}

function checkQty_Result(result)
{
	//alert("checkQty_Result");			
	if (result[0].QUANTITYERR == '')
	{
		userHasUpdatedField = true;
 		if(g_currentShoppingCartPage == "shoppingCartPayment")
 			refreshPaymentPage("");
 		else
 			refreshShoppingCartPage("");
	}
	else
	{
		msg = result[0].QUANTITYERR;				
			
		itemMSG = msg.split('|');				
		innerMsg = msg_errorNotEnoughQuantity;
				
		while (innerMsg.indexOf('::QTY_AVAIL::') != -1)
		{
			innerMsg = innerMsg.replace('::QTY_AVAIL::',itemMSG[4]);
		}
		innerMsg = '<strong>' + itemMSG[0] + '</strong><br>' + innerMsg;
		
		
		var error_TD_id = 'error_' + QtyTarget;
		var error_DIV_id = 'errorMessage_' + QtyTarget;
		$(error_TD_id).style.display = 'block'; 
		$(error_DIV_id).innerHTML = innerMsg;
		window.setTimeout(function()
									{
										$(error_TD_id).style.display='none';
										$(error_DIV_id).innerHTML = '';
									}, 6900);

		cc = 1;
		currQty = "document.getElementById('currentQty_" + cc + "')";
		newQty = "document.getElementById('qty_" + cc + "')";
		
		while(eval(currQty))
		{
			currQtyObj = eval(currQty);
			newQtyObj = eval(newQty);
			
			newQtyObj.value = currQtyObj.value;
			
			cc = cc + 1;
			currQty = "document.getElementById('currentQty_" + cc + "')";
			newQty = "document.getElementById('qty_" + cc + "')";
			
		}
	}
}

function CheckQtyThenAddMultiOrder(ID,origQtyID,desc,row,ukey,orderID,lineItemNo,crntQty,referenceOrderNumber)
{
	$('checkoutB').style.display = 'none';
	if($('checkoutB1'))
		$('checkoutB1').style.display = 'none';
	$('buttonProcessing').style.display = '';

 	var CFID = g_cfid;
	var CFTOKEN = g_cftoken;
	var CFID_CFTOKEN = "";
	if(CFID.length > 0) {
		CFID_CFTOKEN = CFID+"_"+CFTOKEN;
	}
	
	QtyVal = $(ID).value;
	QtyTarget = ID;
	OrigVal = $(origQtyID).value;

	errDiv = $('error_qty_'+''+row);
	errDiv.style.display = 'none';
	
	skuIDD=eval($('skuID_'+''+row));
	skuID = skuIDD.value;
	
	if($('skuID_'+''+row))
	{
		sizeIDD=eval($('skuID_'+''+row));
		sizeIDD = sizeIDD.value;
	}
	else
	{
		sizeIDD = 'good';
	}
	
	if (OrigVal != QtyVal)
	{
	
		if (sizeIDD == '')
		{
			showAlert({message:'#ShoppingCartXmlStruct.errorssize#',closeBText:'x',cssClass:'alertboxSmall'});
			$(ID).value = OrigVal;
			$('checkoutB').style.display = '';
			if($('checkoutB1'))
				$('checkoutB1').style.display = '';
			$('buttonProcessing').style.display = 'none';
		}
		else if (QtyVal == '')
		{
			showAlert({message:'#errorXMLStruct1.errorqty#' + desc,closeBText:'x',cssClass:'alertboxSmall'});
			$('checkoutB').style.display = '';
			if($('checkoutB1'))
				$('checkoutB1').style.display = '';
			$('buttonProcessing').style.display = 'none';
		}	
		else if(_isInteger(QtyVal))	
		{
			DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'CheckMultiorderThenUpdate',skuID,QtyVal,row,origQtyID,lineItemNo,crntQty,referenceOrderNumber,orderID,CFID_CFTOKEN,false,true,CheckMultiorderThenUpdate_Result);
		}
		else
		{
			showAlert({message:msg_errorNumberQty + ' ' + desc,closeBText:'x',cssClass:'alertboxSmall'});
			$('checkoutB').style.display = '';
			if($('checkoutB1'))
				$('checkoutB1').style.display = '';
			$('buttonProcessing').style.display = 'none';
		}
	} else {	
		$('checkoutB').style.display = '';
		if($('checkoutB1'))
			$('checkoutB1').style.display = '';
		$('buttonProcessing').style.display = 'none';
	}
}

function extimateTaxesPostalCodeOnblur(orderID,ukey,taxOnShippingInd,lang,messagetext ){
	hideButton(true);
	g_extimateTaxText = messagetext;
	countryID = $('country_id').value;
	postalcode = $('ZipCode').value;
	if (document.getElementById("Discounts")) {
		discountValue = document.getElementById("Discounts").value;
	} else {
		discountValue = '';
	}
	try
	{
		DWREngine._execute(_cfShoppingCartFunctions, null, 'orderEstimateTaxesNoShippingDetailsPostalCode', orderID, lang, countryID, postalcode, ukey, taxOnShippingInd, discountValue, orderHeader_result);
		//alert('line 776');
	}
	catch(error)
	{
		//alert('line 779');
	}
}

function orderHeader_result(result)
{ 
	var taxesResult=new Array("$0.00","$0.00","$0.00","$0.00","$0.00","$0.00","$0.00"); 
	if (result) {
	taxesResult = result.split("~");
	}

	taxResult1 = '';
	taxResult3 = '';
	document.getElementById("estimateTax").innerHTML = "";
	
	taxResult1 = taxesResult[1];
	taxResult3 = taxesResult[3];
	// remove ï¿½ simbol
	taxResult1 = taxResult1.replace('\u00a3','');
	taxResult3 = taxResult3.replace('\u00a3','');
	if(taxesResult[1] != "$0.00" && taxResult1 != "0.00" ){
		document.getElementById("estimateTax").innerHTML += "<fieldset><label>" + g_extimateTaxText + "</label><div class='taxAmount'>" + taxesResult[1] + "</div><div class='taxType'>" + taxesResult[0] + "</div></fieldset>";	
	
		if(taxesResult[3] != "$0.00" && taxResult3 != "0.00"){
			document.getElementById("estimateTax").innerHTML += "<fieldset><label> &nbsp; </label><div class='taxAmount'>" + taxesResult[3] + "</div><div class='taxType'>" + taxesResult[2] + "</div></fieldset>";
		}
		document.getElementById("estimateTax").style.display = "block";
	}else if(taxesResult[3] != "$0.00" && taxResult3 != "0.00"){
		document.getElementById("estimateTax").innerHTML += "<fieldset><label>" + g_extimateTaxText + "</label><div class='taxAmount'>" + taxesResult[3] + "</div><div class='taxType'>" + taxesResult[2] + "</div></fieldset>";
		document.getElementById("estimateTax").style.display = "block";			
	}else
		document.getElementById("estimateTax").style.display = "none";

 	if(taxesResult[7] != "$0.00") {
 		$("oversizeShipping").style.display ="block";
 		$("surchargeshow").style.display="block";
 		$("surchargeAmt").innerHTML=taxesResult[7];
 	} else {
 		$("oversizeShipping").style.display ="none";
 		$("surchargeshow").style.display="none";
 	}

	
	//Update total
	if(taxesResult[4] != "$0.00") {
		document.getElementById("totalPrice").innerHTML = taxesResult[4]; 	
	}
	hideButton(false);
}


function refreshShippingMethodByMultiOrder(arguments)
{
	if ( !$( "ShopShippingMethod_" + arguments.orderId ) ) {
		hideButton( false );
		return false;
	}
	
	itemTypes = j$( "#ItemTypeIDs_" + arguments.orderId ).val();

	countryID = $('country_id').value;
 	DWREngine._execute(_cfPaymentsFunctions, null, 'callgetShippingMethodMultiOrder', countryID, arguments.orderId, itemTypes, refreshShippingMethodByMultiOrder_Result);
}

function refreshShippingMethodByMultiOrder_Result(result)
{
	shippingResult = result.split("~");
	
	for (i=0; i<shippingResult.length; i++) {
		shippingResult1 = shippingResult[i].split("|");
		if ($('selectShippingMethod_'+shippingResult1[0])) $('selectShippingMethod_'+shippingResult1[0]).innerHTML = shippingResult1[1];
	}
	
}


function CheckMultiorderThenUpdate_Result(result)
{

	if (result[0].QUANTITYERR.SUCCESS == 'true'){
		idx = result[0].ORIGQTYID.split('_')[1];
		$(result[0].ORIGQTYID).value = result[0].ORIGQTY;
		
		if ($('cartDetailsQty_'+idx))
			$('cartDetailsQty_'+idx).innerHTML = result[0].ORIGQTY;
		
		if ($('subTotalAmount_'+result[0].ORDERID))
			$('subTotalAmount_'+result[0].ORDERID).innerHTML = result[0].EXTENDEDPRICE;
		
		if ($('shippingSurcharge') && result[0].SURCHARGEAMOUNT != '' && parseFloat(result[0].SURCHARGEAMOUNT.replace('$','')) > 0){
			$('shippingSurcharge').style.display = '';
			$('surchargeDesc').innerHTML = result[0].SURCHARGEAMOUNT;
		}

		if ($('shipping'))
			$('shipping').innerHTML = result[0].SHIPPINGAMOUNT;

		if ($('subtotNoTax'))
			$('subtotNoTax').innerHTML = result[0].EXTENDEDPRICE;

		
		if ($('taxValue') && result[0].TOTALTAXES != '' && parseFloat(result[0].TOTALTAXES.replace('$','')) > 0){
			$('taxvalueWrapper').style.display = '';
			$('taxValue').innerHTML = result[0].TOTALTAXES;
		}
		
		if ($('tax1value') && result[0].TAX1 != '' && parseFloat(result[0].TAX1.replace('$','')) > 0){
			$('tax1valueWrapper').style.display = '';
			$('tax1value').innerHTML = result[0].TAX1;
		}
		
		if ($('tax2value') && result[0].TAX2 != '' && parseFloat(result[0].TAX2.replace('$','')) > 0){
			$('tax2valueWrapper').style.display = '';
			$('tax2value').innerHTML = result[0].TAX2;
		}
		
		if ($('totalPrice'))
			$('totalPrice').innerHTML = result[0].TOTALAMOUNT;	
		
		refreshShippingMethodByMultiOrder({orderId:result[0].ORDERID});

	} else {
		msg = result[0].QUANTITYERR.MESSAGE;				
		itemMSG = msg.split('|');				
		innerMsg = msg_errorNotEnoughQuantity;
				
		while (innerMsg.indexOf('::QTY_AVAIL::') != -1)
		{
			innerMsg = innerMsg.replace('::QTY_AVAIL::',itemMSG[4]);
		}
		innerMsg = '<strong>' + itemMSG[0] + '</strong><br>' + innerMsg;
		
		var error_TD_id = 'error_' + QtyTarget;
		var error_DIV_id = 'errorMessage_' + QtyTarget;
		$(error_TD_id).style.display = 'block'; 
		$(error_DIV_id).innerHTML = innerMsg;
		window.setTimeout(function()
									{
										$(error_TD_id).style.display='none';
										$(error_DIV_id).innerHTML = '';
									}, 6900);
	
		cc = 1;
		currQty = "document.getElementById('currentQty_" + cc + "')";
		newQty = "document.getElementById('qty_" + cc + "')";
		
		while(eval(currQty))
		{
			currQtyObj = eval(currQty);
			newQtyObj = eval(newQty);
			
			newQtyObj.value = parseInt(currQtyObj.value);
			
			cc = cc + 1;
			currQty = "document.getElementById('currentQty_" + cc + "')";
			newQty = "document.getElementById('qty_" + cc + "')";
			
		}
	}
	$('checkoutB').style.display = '';
	if($('checkoutB1'))
		$('checkoutB1').style.display = '';
	
	$('buttonProcessing').style.display = 'none';
}




function checkQtyThenAdd(ID,origQtyID,desc,row,orderID,lineItemNo,crntQty)
{

	QtyVal = $(ID).value;
	QtyTarget = ID;
	OrigVal = $(origQtyID).value;
	
	errDiv = $('error_qty_'+''+row);
	errDiv.style.display = 'none';
	
	skuIDD=eval($('skuID_'+''+row));
	skuID = skuIDD.value;
	
 	var CFID = g_cfid;
	var CFTOKEN = g_cftoken;
	var CFID_CFTOKEN = "";
	if(CFID.length > 0)
	{
		CFID_CFTOKEN = CFID+"_"+CFTOKEN;
	}
	
	if($('skuID_'+''+row))
	{
		sizeIDD=eval($('skuID_'+''+row));
		sizeIDD = sizeIDD.value;
	}
	else
	{
		sizeIDD = 'good';
	}
	
	if (OrigVal != QtyVal)
	{
	
		if (sizeIDD == '')
		{
			showAlert({message:msg_errorSize,closeBText:'x',cssClass:'alertboxSmall'});
			$(ID).value = OrigVal;
		}
		else if (QtyVal == '')
		{
			showAlert({message:msg_errorQty + " " + desc,closeBText:'x',cssClass:'alertboxSmall'});
		}	
		else if(_isInteger(QtyVal))	
		{		
			if(QtyVal == 0)
			{
				deleteOrderSkuAjax(row,lineItemNo);
			}		
			else
			{
				DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'CheckStyleAvailableThenAdd',skuID,QtyVal,row,origQtyID,lineItemNo,crntQty,CFID_CFTOKEN,checkQtyThenAdd_Result);
			}									
		}
		else
		{
			showAlert({message:msg_errorNumberQty + " " + desc,closeBText:'x',cssClass:'alertboxSmall'});
		}
	
	}
}

function checkQtyThenAdd_Result(result)
{

	if (result[0].QUANTITYERR.SUCCESS == 'true')
	{
		//alert("checkQtyThenAdd_Result");
		AddResult = result[0].UPDATEORDERDET;
		lineItemResult = AddResult.split("~");
		
		theRow =  lineItemResult[4];
		
		if ($("totalPrice")) $('totalPrice').innerHTML = lineItemResult[3];
		if ($('itemTotal_'+theRow)) $('itemTotal_'+theRow).innerHTML = lineItemResult[10];
		
		
		shippingCost = lineItemResult[11];
		shippingCostToShow = lineItemResult[12];
		
		$(result[0].ORIGQTYID).value = lineItemResult[5];
		//alert('test');
		if(document.getElementById('freeShippingBanner') && document.getElementById('freeShippingBanner').style.display != 'none')
		{
			if(parseInt(shippingCost) == 0)
			{
				document.getElementById('shippingAmount').innerHTML ='free shipping'; 
			}
			else
			{
				document.getElementById('shippingAmount').innerHTML = shippingCostToShow; 
			}
		}

	    document.location.href = g_linkUpdateCartServlet;
	}
	else
	{
		msg = result[0].QUANTITYERR.MESSAGE;
		//alert(msg);				
		itemMSG = msg.split('|');				
		innerMsg = msg_overMaxQuantity;
				
		while (innerMsg.indexOf('::QTY_AVAIL::') != -1)
		{
			innerMsg = innerMsg.replace('::QTY_AVAIL::',itemMSG[4]);
		}
		innerMsg = '<strong>' + itemMSG[0] + '</strong><br>' + innerMsg;
		
		//Make proper html code
		innerMsg = innerMsg.replace(/&lt;/gi,"<");
		innerMsg = innerMsg.replace(/&gt;/gi,">");
						
		//showAlert({message:innerMsg,closeBText:'x',cssClass:'alertboxSmall'});
		var error_TD_id = 'error_' + QtyTarget;
		var error_DIV_id = 'errorMessage_' + QtyTarget;
		$(error_TD_id).style.display = 'block'; 
		$(error_DIV_id).innerHTML = innerMsg;
		window.setTimeout(function()
									{
										$(error_TD_id).style.display='none';
										$(error_DIV_id).innerHTML = '';
									}, 6900);

		cc = 1;
		currQty = "document.getElementById('currentQty_" + cc + "')";
		newQty = "document.getElementById('qty_" + cc + "')";
		
		while(eval(currQty))
		{
			currQtyObj = eval(currQty);
			newQtyObj = eval(newQty);
			
			newQtyObj.value = currQtyObj.value;
			
			cc = cc + 1;
			currQty = "document.getElementById('currentQty_" + cc + "')";
			newQty = "document.getElementById('qty_" + cc + "')";
			
		}
	}
}

function colorOnChange(storeID,itemID,colorID,lang,currentRow)
{
 	g_currentRow = currentRow;
 	if($('dimensionID')){
 		DWREngine._execute(_cfShoppingCartFunctions, null,'callitemDimensionByColor',storeID,itemID,colorID,lang,colorOnChange_Result);
 	}else{
 		DWREngine._execute(_cfShoppingCartFunctions, null,'callitemSizeByColor',storeID,itemID,colorID,'',lang,dimensionOnChange_Result);
 	}
 }

function colorOnChange_Result(result)
{
 	if ((g_currentRow == null) || (g_currentRow == 'undefined')) {
 		dimensionDD = $('dimensionID');
 	}else {
 		dimensionDD = $('dimensionID_'+g_currentRow);
 	}
 	
 	if ((g_currentRow == null) || (g_currentRow == 'undefined')) {
 		sizeDD = $('sizeID');
 	}else {
 		sizeDD = $('skuID_'+g_currentRow);
 	}
 	
 	dimensionDD.options.length = 1;
 	sizeDD.options.length = 1;
 	dimensionDD.options[0] =  new Option(msg_selectDimension,'');
 	
 	
 	for (i=0;i<result.length;i++)
 	{
 		dmValue = result[i]['ITEM_ID'] + '|' + result[i]['COLOR_ID'] + '|' + result[i]['DIMENSION_ID'];
 		dimensionDD.options[i+1] = new Option(result[i]['DIMENSION_DESCRIPTION'],dmValue);
 		dimensionDD.options[i+1].id = result[i]['DIMENSION_DESCRIPTION'];
 	}
 	
}

function dimensionOnchange(values,storeID,lang,currentRow)
{
	if (values != ''){
		v = values.split('|');
		itemID = v[0];
		colorID = v[1];
		dimensionID = v[2];
	 	g_currentRow =currentRow;
	 	DWREngine._execute(_cfShoppingCartFunctions, null,'callitemSizeByColor',storeID,itemID,colorID,dimensionID,lang,dimensionOnChange_Result);
 	}
}


function dimensionOnChange_Result(result)
{
 	if ((g_currentRow == null) || (g_currentRow == 'undefined')) {
 		sizeDD = $('sizeID');
 	}else {
 		sizeDD = $('skuID_'+g_currentRow);
 	}
 	
	sizeDD.options.length = 1;
	sizeDD.options[0] =  new Option(msg_selectSize,'');
 	
 	for (i=0;i<result.length;i++)
 	{
 		sizeDD.options[i+1] = new Option(result[i]['SIZE_DESCRIPTION'],result[i]['SKU_ID']);
 		sizeDD.options[i+1].id = result[i]['SIZE_DESCRIPTION'];
 		if(result.length == 1)
 			sizeDD.options[i+1].selected = true;
 	}
 	
}

function currencyFormat(num, lang){
	var loc = {};
	loc.num = num;
	loc.num = loc.num.toString().replace(/\$|\,/g,'');
	if (isNaN(loc.num))
		loc.num = "0";

	loc.lang = lang || "eng";

	loc.sign = (loc.num == (loc.num = Math.abs(loc.num)));
	loc.num = Math.floor(loc.num*100+0.50000000001);
	loc.cents = loc.num%100;
	loc.num = Math.floor(loc.num / 100).toString();
	if(loc.cents < 10)
		loc.cents = "0" + loc.cents;
	
	for (loc.i = 0; loc.i < Math.floor((loc.num.length-(1+loc.i))/3); loc.i++)
		loc.num = loc.num.substring(0,loc.num.length-(4*loc.i+3))+','+ loc.num.substring(loc.num.length-(4*loc.i+3));

	return (((loc.sign)?'':'-') + (loc.lang == 'eng'?'$':'') + loc.num + '.' + loc.cents + (loc.lang == 'fre'?'$':''));
}

function dummy_Result(result)
{	

	rValues = result.split('~');
	
	/*
	discountCode = $('Discounts').value;
	if (discountCode != ''){
		checkDiscount(g_ukey,g_refresh_page);
		return;
	}
	*/
	
	if ( g_refresh_page ) {
		if(g_currentShoppingCartPage == "shoppingCartPayment")
			refreshPaymentPage("");
		else
			refreshShoppingCartPage("");
	} else {
		if(g_currentShoppingCartPage == "shoppingCartPayment"){
			if (rValues[2] > 0){
				if ($('totalPromotion')) $('totalPromotion').innerHTML = rValues[0];
				if ($("totalPrice")){ 
					$('totalPrice').innerHTML = rValues[1];
					if (parseFloat(rValues[4]) > 0) $('totalPrice').innerHTML = rValues[5];
				}
				if ( $('promotiondiscounttax') )
					$('promotiondiscounttax').style.display = '';
			} else {
				if ( $('promotiondiscounttax') )
					$('promotiondiscounttax').style.display = 'none';
				if ($("totalPrice")) {
					//$('totalPrice').innerHTML = rValues[1];
					if (parseFloat(rValues[4]) > 0) $('totalPrice').innerHTML = rValues[5];
				}
			}
		}
		else
			refreshShoppingCartPage("");
	
	}
				
}

function deleteOrderAjax()
{
	var args = {
			method: "deleteOrder"
		,	orderID: j$( "#orderID" ).val()
	};
	j$.post(
			siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
		,	args
		,	deleteOrderSkuAjax_result
		,	"json"
	);
}
	
function deleteOrderSkuAjax(row,lineItemNumber)
{
	skuIDD=eval($('skuID_'+''+row));
	skuID = skuIDD.value;
	
	DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'deleteOrderSkuAjax',skuID,row,lineItemNumber,deleteOrderSkuAjax_result);
}		

function deleteOrderSkuAjax_result(result)
{
	//Check discount because if we delete an item, it can affect some discount requirement
	if(j$("#Discounts").val() != "") {
		checkDiscount(true);
	} else {			
		document.location.href = g_linkUpdateCartServlet;
	}
}

function deleteOrderSkuNow(row)
{
	skuIDD=$('skuID_'+row);
	skuID = skuIDD.value;

	document.deleteOrderSku.skuID.value = skuID;
	document.deleteOrderSku.submit();
}

function editAddress(action,addType,elem,table,billAddressId,shipAddressId,loginGuest,BillingIsShipping)
{
	if(!addType){
		addTypeParam = "";
	}
	else{
		addTypeParam = "&addressType="+addType;
	}
	
	if(!billAddressId){
		billAddressIdParam = "";
	}
	else{
		billAddressIdParam = "&billAddressId="+billAddressId;
	}
	
	if(!shipAddressId){
		shipAddressIdParam = "";
	}
	else{
		shipAddressIdParam = "&shipAddressId="+shipAddressId;
	}
	
	if(!loginGuest){
		loginGuest = "";
	}
	else{
		loginGuest = "&loginGuest="+loginGuest;
	}	
	
	if (BillingIsShipping === undefined) {
		BillingIsShipping= "";
	} else {
		BillingIsShipping = "&BillingIsShipping="+BillingIsShipping;
	}
	
 	if (action =='edit')
 	{
		window.location.href = g_linkUpdateUserProfile+addTypeParam+billAddressIdParam+shipAddressIdParam+loginGuest+BillingIsShipping;
 	}
 	else
 	{
 	  	$('action').value = action;
 	  	$('addresstype').value = addType;
		$('addressID').value ='';
		$('whatTable').value = table;
	 	
	 	if(!document.all)
	 	{
	 		document.forms['gotoFormBilling'].submit();
	 	}
	 	else
	 	{
		 	document.gotoFormBilling.submit();
	 	}
 	}
}

function editPickupAddress(){
	window.location.href = g_linkUpdateCartServlet;
}

function getElementsByName(objCol,els)
{
	objEls = els.split(',');
	retObj = new Array();
	i=0;
	for(o=0;o<objCol.length;o++)
	{
		checkId = objCol[o].id
		for(e=0;e<objEls.length;e++)
		{
			if(checkId.toUpperCase().indexOf(objEls[e].toUpperCase())>=0)
			{
				retObj[i] = objCol[o];
				i++
			}		
		}
	}	
	return retObj;
		
}

function getShopCrossSellDimension(val,itemID){

	v = val.split('|');
	colorID	= v[0];
	DWREngine._execute(_cfCatLevelsLocation, null, 'getDimensionsByColorItem',itemID,colorID,g_actualLang,getShopCrossSellDimension_result);

}

function getShopCrossSellDimension_result(result){

	for(i=0;i<result.length;i++)
	{
		dmValue = result[i]['ITEM_ID'] + '|' + result[i]['COLOR_ID'] + '|' + result[i]['DIMENSION_ID'];
		option = new Option(result[i].DIMENSION_DESC,dmValue);				
		obj = 'ShopCrossSellDimension_' + result[i].ITEM_ID;	
		
		if (i == 0) {
			document.getElementById(obj).options.length = 1;
			$('ShopCrossSellSize_' + result[i].ITEM_ID).options.length = 1;
		}
		
		document.getElementById(obj).options[i+1] = option;
		
		if(result.length == 1){
			document.getElementById(obj).selectedIndex = 1;
			document.getElementById(obj).onchange();
		}
	}
	
}

function getShopCrossSellSize(val)
{

 	if (val != ''){
	 	v = val.split('|');
	 	itemID = v[0];
		colorID	= v[1];
		dimensionID = v[2];
		DWREngine._execute(_cfCatLevelsLocation, null, 'getSizesByColorItem',itemID,colorID,dimensionID,g_actualLang,'in',getShopCrossSellSize_result);
	}
			
}

function getShopCrossSellSize_result(result)
{				

	for(i=0;i<result.length;i++)
	{
		option = new Option(result[i].SIZE_DESC,result[i].SKU_ID);				
		obj = 'ShopCrossSellSize_' + result[i].ITEM_ID;	
		
		if(i ==0) document.getElementById(obj).options.length = 1;
		
		document.getElementById(obj).options[i+1] = option;
		
		if(result.length == 1)
			document.getElementById(obj).selectedIndex = 1;
	}
	
}
		
function hideButton(hide)
{
	if(hide)
	{
		if($('checkoutB'))
			$('checkoutB').style.display = 'none';
		
		if($('checkoutB1'))
			$('checkoutB1').style.display = 'none';
		
		if($('buttonProcessing'))	
			$('buttonProcessing').style.display = 'block';
			
		if($('checkoutBend'))	
			$('checkoutBend').style.display = 'none';
	}
	else
	{
		if($('checkoutB'))
			$('checkoutB').style.display = 'block';
		
		if($('checkoutB1'))
			$('checkoutB1').style.display = 'block';
		
		if($('buttonProcessing'))		
			$('buttonProcessing').style.display = 'none';
		
		if($('checkoutBend'))	
			$('checkoutBend').style.display = 'block';
	}
}

function narrowPickupStores () {
	
	j$.getJSON(
			siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
		,	{
					method: "narrowInStorePickupLocations"
				,	country_id: j$( "#country_id" ).val()
				,	postal_code: j$( "#pickupPostalCode" ).val()
				,	radius: j$( "#pickupRadius" ).val()
			}
		,	narrowPickupStore_result
	);
	
};

function narrowPickupStore_result ( result ) {
	
	var jStores = j$( "#ShopPickupLocation" );
	
	jStores.children( "option:gt(0)" ).remove();
	
	for ( var i=0; i < result.length; i++ )
		jStores.append( "<option value='" + result[ i ].LOCATION_ID + "'>" + result[ i ].LOCATION_NAME + "</option>" );
	
};

function onChangeShippingOrPickup( init ){

	if($('shippingOrPickup-shipping') && $('shippingOrPickup-pickup')){
	
		if($('shippingOrPickup-pickup').checked == true){
		
			$('ShopShippingMethod').selectedIndex = 0;
			$('ShopShippingMethod').style.display = "none";
			$('ShippingSelectedIndex').value = g_pickupShippingMethodID; 
			
			$('ShopPickupLocation').style.display = "block";
			$( "narrow-instore-pickup" ).style.display = "block";
			
		}else{			
			$('ShopPickupLocation').selectedIndex = 0;
			$('ShopShippingMethod').style.display = "block";
			$('ShippingSelectedIndex').value = "";
						
			$('ShopPickupLocation').style.display = "none";
			$( "narrow-instore-pickup" ).style.display = "none";
		}			
	
	}
	if ( !init )
		checkDiscount( false );
	
}

function refreshShippingCountry_Result(result)
{

	var shipping = '';
	shipping = document.getElementById("ShopShippingMethod");
	previousSelected = document.getElementById("ShopShippingMethod").selectedIndex;

 	//previousSelected = document.getElementById(shipping).selectedIndex;
 	shippingResult = result.split("~");
 	shipping.options.length = 1;
	for (i=0; i<shippingResult.length-1; i++) {
		shippingResult1 = shippingResult[i].split("|");
		shipping.options[i+1] = new Option(shippingResult1[0],shippingResult1[1]);
	}
	
	shipping.selectedIndex = previousSelected;
	shippingMethodvalue = shipping[previousSelected].value;


	checkDiscount(false);
	
		if (document.getElementById("ShopShippingMethod"))
			{
				document.getElementById("ShopShippingMethod").disabled = false;
			} else {
				document.getElementById("shippingMethodID").disabled = false;
			}
}

function refreshShippingMethod()
{
	if ( !$("SHIPPINGMETHODID") && !$("ShopShippingMethod") ) {
		hideButton( false );
		return false;
	}
	
	if(document.getElementById('country_id')){
 		countryID = $('country_id').value;   
	}else{
		countryID = 'US';	
	}
	
 	DWREngine._execute(_cfPaymentsFunctions, null,'callgetShippingMethod',countryID,refreshShippingMethod_Result);
}

function refreshShippingMethod_Result(result)
{
	var myShippingMethodSelectBox = "";
	
	shippingResult = result.split("~");
	
	if($("SHIPPINGMETHODID")){
		//Payment page
		myShippingMethodSelectBox = $("SHIPPINGMETHODID");
	}else{
		//Shopping cart page
		myShippingMethodSelectBox = $("ShopShippingMethod"); 	
 	}	
 	
	try
	{
		previusSelected = myShippingMethodSelectBox.selectedIndex;
 		myShippingMethodSelectBox.options.length = 1;
		for (i=0; i<shippingResult.length-1; i++) {
			shippingResult1 = shippingResult[i].split("|");
			myShippingMethodSelectBox.options[i+1] = new Option(shippingResult1[0],shippingResult1[1]);
		}
	
		myShippingMethodSelectBox.selectedIndex = previusSelected;
		shippingMethodvalue = myShippingMethodSelectBox.value;
	
		if($("SHIPPINGMETHODID")){
			//Payment page
			updateShippingPayment(shippingMethodvalue);
		}else{
			//Shopping cart page
			UpdateShipping(shippingMethodvalue);			
		}
	}
	catch (err)
	{
		// do nothing
	}	
}

function refreshPaymentPage(errorPopup){
	var oPaymentMethod = getPaymentMethodSelected();
 	linkRefresh = g_linkUpdatePaymentServlet;
	payMethod = "";
	
	if (oPaymentMethod == 'radioPaymentPaypal'){
		payMethod = 'PayPal';
	} else if (oPaymentMethod == 'radioPaymentCC'){
		payMethod = 'CreditCard';
	} else if (oPaymentMethod == 'radioPaymentInterac'){
		payMethod = 'Interac';
	} else if (oPaymentMethod == 'radioPaymentPO'){
		payMethod = 'PO';
	} else if (oPaymentMethod == 'radioPaymentSampleAccount'){
		payMethod = 'SampleAccount';
	} else if (oPaymentMethod == 'radioPaymentRequestQuote'){
		payMethod = 'QUOTE';
	}
	
	if(errorPopup != "")
		linkRefresh += '&errorPopup=' + errorPopup;
	
 	window.location.href = linkRefresh + '&paymentMethod=' + payMethod;		
}

function refreshShoppingCartPage(errorPopup){
 	linkRefresh = g_linkUpdateCartServlet;

	if(errorPopup != "")
		linkRefresh += '&errorPopup=' + errorPopup;
	
 	window.location.href = linkRefresh;		
}

function removeGiftwrap_Result(result){
	//window.location.href = g_linkUpdateCartServlet;
	window.location.reload();
  	showAlert({message:msg_giftWrapRemoved ,closeBText:'x',cssClass:'alertboxSmall'});	  
}

function removeSelectGiftWrap(totalCount,ukey,orderID,currencyID){
	for(var i=1;i<=totalCount;i++){

  		if($('giftwrapTypeDiv_'+i).className == "giftwrapHighlight"){
  	 		$('giftwrapTypeDiv_'+i).className="giftwrapNotHighlight";
  	 		$('selectGiftWrapType').value='';
  	 		oldGiftWrapsku=$('oldSelectGiftWrap').value;
  	 		oldGiftWrapLineNo=$('oldSelectGiftWrapLineNo').value;
  	 		CFID = g_cfid;
			CFTOKEN = g_cftoken;
	
			CFID_CFTOKEN = "";
			if(CFID.length > 0)
			{
				CFID_CFTOKEN = CFID+"_"+CFTOKEN;
			}
	
  	 		DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'removeGiftwrap',CFID_CFTOKEN,oldGiftWrapsku,oldGiftWrapLineNo,ukey,orderID,currencyID, removeGiftwrap_Result);
   	 	}
   	} 
}
	
function sizeOnChange(skuID)
{
	DWREngine._execute(_cfPaymentsFunctions, null,'callupdateFreeItemOrder',skuID,null_return);
		
}
				
function shopCrossAddToBag(itemID,productType)
{
	err = '';
	
	if (productType != 'SINGLE_SKU')
	{
		color = 'ShopCrossSellColor_' + itemID;
		color = document.getElementById(color).options[document.getElementById(color).selectedIndex].value;
					
		size = 'ShopCrossSellSize_' + itemID;
		size = document.getElementById(size).options[document.getElementById(size).selectedIndex].value;
	
		
		if(color == '')
			err = err + msg_errorColor;
		
		if(size == '')
			err = err + msg_errorSize2;
	}
	else
	{
		size = 'skuID_' + itemID;
		size = document.getElementById(size).value;
	}
		
	quantity = 'ShopCrossSellQuantity_' + itemID;
	quantity = document.getElementById(quantity).value;	
		
	if(quantity == '')
		err = err + msg_errorQty;	
	else if (!_isInteger(quantity))
		err = err + msg_errorNumberQty;
	else if (quantity == '0')
		err = err + msg_errorQty;
		
	if(err == '')
	{
		CFID = g_cfid;
		CFTOKEN = g_cftoken;
	
		CFID_CFTOKEN = "";
		if(CFID.length > 0)
		{
			CFID_CFTOKEN = CFID+"_"+CFTOKEN;
		}
				
						
		DWREngine._execute(_cfShoppingCartFunctionsLocation, null, 'addStyles',g_actualLang,'','',itemID,CFID_CFTOKEN,size,quantity,shopCrossAddToBag_Result);
	}
	else
		showAlert({message:err,closeBText:'x',cssClass:'alertboxSmall'});
		
}

function shopCrossAddToBag_Result(result)
{
		if (result[0].QUANTITYERR.MESSAGE != '')
		{
			
			msg = result[0].QUANTITYERR.MESSAGE;	
			msg = msg.split('~');			
			showMessage = '';
			
			for(i=0;i<msg.length;i++)
			{
				if(showMessage != '')
					showMessage = showMessage + '<br><br>';
				
				itemMSG = msg[i].split('|');
				
				
				innerMsg = msg_errorNotEnoughQuantity;
				
				while (innerMsg.indexOf('::QTY_AVAIL::') != -1)
					innerMsg = innerMsg.replace('::QTY_AVAIL::',itemMSG[4]);
					
				while (innerMsg.indexOf('::ITEM_DESC::') != -1)
					innerMsg = innerMsg.replace('::ITEM_DESC::',itemMSG[0]);
				
				innerMsg = '<strong>' + itemMSG[0] + '</strong><br>' + innerMsg;
			
				showMessage = showMessage + innerMsg;
			}			
			
			
			showAlert({message:showMessage,closeBText:'x',cssClass:'alertboxSmall'});
		}
		else
		{
			window.location.href = g_linkUpdateCartServlet;
		}	
}

function ShoppingBagGoToExpressPaypalCheckoutCheckShipping(amtRows)
{
	ShopShippingMethod = document.getElementById('ShopShippingMethod');
	err = ''
	
	if(ShopShippingMethod.options[ShopShippingMethod.selectedIndex].value == '')
		err =  msg_errorShippingMethod;

	for(i=1;i<=amtRows;i++)
	{
		if($('skuID_'+i))
		{
			if($('skuID_'+i).options)	
			{
				sizeDD = $('skuID_'+i);

				if(sizeDD.options[sizeDD.selectedIndex].value == '')
				{
					err = err + '<br>' + msg_errorSize;
					break;
				}					
				
			}
		}
	}

	if(err == '')
		window.location.href = g_linkShoppingCartPaypalExpress;
	else
		showAlert({message:err,cssClass:'alertboxSmall'});
	
}
						
function sizeOnchangedShoppingCart(orderId,oldSkuId,NewSkuId,row,itemDesc,lineItemNumber)
{	
 	if (NewSkuId != '')
 	{		 		
		 	g_oldSizeSelection = $(oldSkuId).value + '|' + row + '|' + oldSkuId;
		 	g_currentRow = row;
		 	qty=eval($('qty_'+''+row));
		 	qty=qty.value;
		 	skuIDD=eval($('skuID_'+''+row));
		 	skuIDD.value = NewSkuId;
		 	oldSKUObj = document.getElementById(oldSkuId)
		 	oldSkuId = oldSKUObj.value;
		 	sku_id_row = 'skuID_'+row
		 	oldSKUObj.value = NewSkuId;
		 	document.getElementById('oldskuID_'+''+row).value=NewSkuId;
		 	DWREngine._execute(_cfPaymentsFunctions, null,'callupdateOrderDetailsSKU',g_ukey,orderId,oldSkuId,NewSkuId,qty,row,lineItemNumber,sizeOnchangedShoppingCart_Result);											
 	}
}
 		
function sizeOnchangedShoppingCart_Result(result)
{	

	lineItemResult = result[1].split("~");
	if (result[0] == 'true')
	{
		if ($("totalPrice")) $('totalPrice').innerHTML = lineItemResult[4];
		if($('itemTotal_'+lineItemResult[6])!=null) {$('itemTotal_'+lineItemResult[6]).innerHTML = lineItemResult[0];}
		if($('itemPrice_'+lineItemResult[6])!=null) {$('itemPrice_'+lineItemResult[6]).innerHTML = lineItemResult[5];}
		
		if(g_currentShoppingCartPage == "shoppingCartPayment")
			document.location.href = g_linkUpdatePaymentServlet;
		else
			document.location.href = g_linkUpdateCartServlet;
		
	}
	else
	{

		undoSelection = g_oldSizeSelection;				
								
		undoSelection = undoSelection.split("|");
		
		
		if($('sizeDrp_'+undoSelection[0]))
		{
			elemID = $('skuID_'+undoSelection[1]);											
			$('sizeDrp_'+undoSelection[0]).selected = true;						
			$(undoSelection[2]).value = undoSelection[0];
		}

		showMessage = '';
		innerMsg = msg_errorNotEnoughQuantity;
		while (innerMsg.indexOf('::QTY_AVAIL::') != -1)
			innerMsg = innerMsg.replace('::QTY_AVAIL::',lineItemResult[4]);
			
		while (innerMsg.indexOf('::ITEM_DESC::') != -1)
			innerMsg = innerMsg.replace('::ITEM_DESC::',lineItemResult[0]);
		
		innerMsg = '<strong>' + lineItemResult[0] + '</strong><br>' + innerMsg;
		showMessage = showMessage + innerMsg;
			
		$('qtyErr_line').value = lineItemResult[5] + ',' + lineItemResult[3];

		//Show an error about qty over the row of the item
		var error_TD_id = 'error_qty_' + lineItemResult[5];
		var error_DIV_id = 'errorMessage_qty_' + lineItemResult[5];

		$(error_TD_id).style.display = 'block'; 
		$(error_DIV_id).innerHTML = showMessage;
		window.setTimeout(function()
									{
										$(error_TD_id).style.display='none';
										$(error_DIV_id).innerHTML = '';
									}, 6900);
	}
		
}

function updateGiftWrapType(count, totalCount){

 	for(var i=1;i<=totalCount;i++)
 	 	$('giftwrapTypeDiv_'+i).className="giftwrapNotHighlight";
 	 
 	$('giftwrapTypeDiv_'+count).className="giftwrapHighlight";
	$('selectGiftWrapType').value=$('GiftWrapType_'+count).value;
}
		 								
function updateshippingDestinationCountry(){
	if (document.getElementById("ShopShippingMethod"))
	{
		document.getElementById("ShopShippingMethod").disabled = true;
	} else {
		document.getElementById("shippingMethodID").disabled = true;
	}
	
 	var shippingCountryID=$('country_id').value;
 	
 	hideButton(true);
 	
 	if($('countrySelected'))
 	{
 		$('countrySelected').value = shippingCountryID;
 	}
 	
/*if ($('ShopShippingMethod'))
{
 	$('ShopShippingMethod').options.length = 1;
} else {
	//$('shippingMethodID').options.length = 1;
	$('shippingMethodID').disabled = false;
}*/
	
 	$('ShopShippingMethod').disabled = true;
 	if(shippingCountryID !=''){
 		DWREngine._execute(_cfPaymentsFunctions, null,'callUpdateshippingDestinationCountry',shippingCountryID,g_ukey,updateshippingDestinationCountry_Result);
		
 	}
}

function updateshippingDestinationCountry_Result(result){
	if ($("ShopShippingMethod"))
		$("ShopShippingMethod").value='';
		
  	if($('ZipCode'))
  		$('ZipCode').value = '';
  	
  	countryID = $('country_id').value;  
 	DWREngine._execute(_cfPaymentsFunctions, null,'callgetShippingMethod',countryID,refreshShippingCountry_Result);

}

function UpdateShippingMethodMultiOrder(shippingMethodvalue,ukey,referenceOrderId)
{
	GlobalUkey = ukey;
	if (shippingMethodvalue == '') shippingMethodvalue = 'null';
	DWREngine._execute(_cfPaymentsFunctions, null,'callapplyShippingMethodMultiOrder',shippingMethodvalue,ukey,referenceOrderId,UpdateShippingMultiOrder_Result);
}

function UpdateShippingMultiOrder_Result(result)
{

	rs = result.split('~');
	if ($('shipping'))
		$('shipping').innerHTML = rs[0];
	if ($('totalPrice'))
		$('totalPrice').innerHTML = rs[2];
	if($('tax1value'))
		$('tax1value').innerHTML = rs[7];
	if($('tax2value'))
		$('tax2value').innerHTML = rs[8];
	
}

function updateDeliveryDate(arguments){
	// set local scope
	var loc = {};
	
	// set default values
	loc.shippingMethodId = arguments.shippingMethodId || 0;
	loc.ukey = arguments.ukey || "";
	loc.orderId = arguments.orderId || 0;
	loc.requestedDate = j$("#hidRequestedDeliveryDate_" + loc.orderId).val();

	loc.arrQSA = [
		"strUKEY=" + loc.ukey,
		"intShippingMethodId=" + loc.shippingMethodId,
		"intOrderId=" + loc.orderId,
		"dtRequestedDate=" + loc.requestedDate
	];

	j$.ajax({
		type: "GET",
		url: siteUrl + "com/b2c/deliveries.cfc?method=getEarliestDateByOrderAndCheckRequested&returnformat=json&" + loc.arrQSA.join("&"),
		dataType: "json", // json
		success: function(objDate){
			j$("#divEarliestDeliveryDate_" + loc.orderId).html(objDate.DTEARLIESTDATE);
			objDelivery["_" + loc.orderId].dtEarliestDeliveryDate = objDate.DTEARLIESTDATE;
			
			objDate.orderId = loc.orderId;
			
			checkForEarlierDate(objDate);
		}
	});		
}

function checkForEarlierDate(arguments){
	var loc = {};
	
	// the user never selected himself a date, we put the earliest
	if (!objDelivery["_" + arguments.orderId].userSelection || arguments.DATESTATE.LT){
		if (objDelivery["_" + arguments.orderId].userSelection && arguments.DATESTATE.LT){
			// user has selected a date, if that date in now newer then the earliest, we must inform him to choose another date.
			showAlert({message:msg_requestedDeliveryDateAjusted,cssClass:'alertboxSmall'});
		}
		setRequestDeliveryDate({orderId:arguments.orderId, dtDate:arguments.DTEARLIESTDATE, userSelection:false});
	}
}

function openEarliestDeliveryDatePicker(arguments){
	var loc = {};
	
	loc.shippingMethodId = j$("#SHIPPINGMETHODID_" + arguments.orderId).val();
	
	loc.ukey = arguments.ukey;
	loc.shippingDetailId = arguments.shippingDetailId;
	
	loc.datePicker = j$("#datepicker_" + arguments.orderId);
	loc.datePicker.datepicker({
		inline: true,
		onSelect: function(dateText, inst){
			// valid the selected date
			checkSelectedDeliveryDate({orderId:inst.id.split('_')[1], dtDate:dateText, shippingDetailId:loc.shippingDetailId, ukey:loc.ukey});
		}
	});
	
	// set date restrictions
	loc.dtEarliestDate = objDelivery.srid > 0 ? objDelivery.today : getStaticEarliestDeliveryDate(arguments);
	loc.arrSplitDate = loc.dtEarliestDate.split('/');
	
	if (loc.arrSplitDate.length == 3){
		loc.datePicker.datepicker('option', 'minDate', new Date(loc.arrSplitDate[2], loc.arrSplitDate[0]-1, loc.arrSplitDate[1]));
	}
}

function getStaticEarliestDeliveryDate(arguments){
	return objDelivery["_" + arguments.orderId].dtEarliestDeliveryDate;
}

function checkSelectedDeliveryDate(arguments){
	var loc = {};
	
	loc.arrQSA = [
		"intOrderId=" + arguments.orderId,
		"ukey=" + arguments.ukey,
		"sale_rep_id=" + objDelivery.srid,
		"sales_rep_type_id=" + objDelivery.srtid,
		"dtDay=" + arguments.dtDate
	];
	
	loc.arguments = arguments;
	
	j$.ajax({
		type: "GET",
		url: siteUrl + "com/b2c/deliveries.cfc?method=getEarliestDateByOrder&returnformat=plain&" + loc.arrQSA.join("&"),
		dataType: "text", // json
		success: function(aDate){
			var iloc = {};
			
			if (aDate != loc.arguments.dtDate)
				showAlert({message:msg_nextAvailableDeliveryDate.replace(/::NEXT_AVAILABLE_DELIVERY::/g, aDate),cssClass:'alertboxSmall'});
			else {
				setRequestDeliveryDate({orderId:loc.arguments.orderId, dtDate:aDate, userSelection:true});
				j$("#datepicker_" + loc.arguments.orderId).datepicker('destroy');
			}
		}
	});	
}

function displayEarlierDateMessage(arguments){
	if (arguments.bln)
		j$("#LessThanLeadTimeMsg_" + arguments.orderId).show();
	else
		j$("#LessThanLeadTimeMsg_" + arguments.orderId).hide();
}

function updateDeliveryDateDB(arguments){
	var loc = {};

	loc.arrQSA = [
		"orderId=" + arguments.orderId,
		"requestedDeliveryDate=" + arguments.requestedDeliveryDate,
		"earliestDeliveryDate=" + getStaticEarliestDeliveryDate(arguments)
	];
	
	loc.arguments = arguments;
	
	j$.ajax({
		type: "GET",
		url: siteUrl + "cfclib/payments.cfc?method=updateRequestedDeliveryDate&returnformat=plain&" + loc.arrQSA.join("&"),
		success: function(bln){
			eval("loc.arguments.bln = " + bln); 
			displayEarlierDateMessage(loc.arguments);
		}
	});	
} 

function setRequestDeliveryDate(arguments){
	j$("#divRequestedDeliveryDate_" + arguments.orderId).html(arguments.dtDate);
	j$("#hidRequestedDeliveryDate_" + arguments.orderId).val(arguments.dtDate);
	objDelivery["_" + arguments.orderId].userSelection = arguments.userSelection || false;
	
	// udpate order
	updateDeliveryDateDB({orderId:arguments.orderId, requestedDeliveryDate:arguments.dtDate});
}

function UpdateShipping(shippingMethodvalue) {
	hideButton(true);
	
 	if (shippingMethodvalue == ''){
 		shippingMethodvalue = 0;
 		// hideButton(false);
	} 
	DWREngine._execute(_cfPaymentsFunctions, null,'callapplyShippingMethod',shippingMethodvalue,g_ukey,UpdateShipping_Result);
}
 
function UpdateShipping_Result(result)
{
 	hideButton(false);
 	shippingCostResult = result.split("~");
 	//alert(shippingCostResult[11]);
 	shipAmt = shippingCostResult[0].replace(' USD',''); 
 	
 	shipAmtNumeric = shipAmt.replace('$','');
 	shipAmtNumeric = shipAmtNumeric.replace(',','.');
 	shipAmtNumeric = shipAmtNumeric.split(".");
 	shipAmtNumeric = shipAmtNumeric[0];
 	
 	// if free shipping
 	if (shippingCostResult[11] == 'true')
 	{
 		shipAmtNumeric = 0;
 	}
 	
 	shippingMethodID = shippingCostResult[10];
 	
 	
 	if($("subTotAmount"))
		$("subTotAmount").innerHTML =shippingCostResult[1];
	
 	
 	if (shipAmtNumeric == '0')
	{
		if(shippingMethodID == 'NULL')
		{
			if($("shippingShow"))
				$("shippingShow").style.display ='none';
			
		}
		else
		{
			if($("shippingShow")){
				$("shippingShow").style.display ='';
				//$("shippingAmount").innerHTML = shipAmt;
				$("shippingAmount").innerHTML = msg_freeShipping;
				$("freeShippingBanner").style.display="block";
			}	
		}
	}
 	else
 	{	
		if($("shippingShow"))
		{
	 		$("shippingShow").style.display ='';
	    	$("shippingAmount").innerHTML = shipAmt;
			$("freeShippingBanner").style.display="none";
	    }	
 	}
 	
 	if(typeof(g_calcTax) != "undefined" && g_calcTax == "true")
 	{
 		extimateTaxesPostalCodeOnblur(j$('#orderID').val(),j$('#taxUkey').val(),j$('#taxOnShippingInd').val(),g_actualLang,j$('#taxMessagetex').val());
 	}
 	else
 	{
 		if ($("totalPrice")) 
 			$("totalPrice").innerHTML = shippingCostResult[3].replace(' USD','');
 	}
   
   if(document.getElementById('country_id')){
	   var shippingCountryID=$('country_id').value;
	 	checkExportCountryeachItem(shippingCountryID);
   }
 	
}

function updateShippingPaymentMultiOrder(shippingMethodvalue,ukey,orderId)
{
 		
 	if (shippingMethodvalue == '') 
 	{
		showAlert({message:msg_errorShippingMethod,cssClass:'alertboxSmall'});
 		$('SHIPPINGMETHODID').value = $('hiddenShippingID').value;
 	}
 	else
 	{
 		$('hiddenShippingID').value = j$('#SHIPPINGMETHODID').val();
 		DWREngine._execute(_cfPaymentsFunctions, null,'callapplyShippingMethodMultiOrder',shippingMethodvalue,ukey,orderId,updateShippingPayment_Result);
 	}
}


function updateShippingPayment(shippingMethodvalue,ETA,showMess)
{
 	if(showMess)
 		showSurchargeMessage = showMess;
 	else
 		showSurchargeMessage = "";
 		
 	if (shippingMethodvalue == '') 
 	{
		showAlert({message:msg_errorShippingMethod,cssClass:'alertboxSmall'});
 		$('SHIPPINGMETHODID').value = $('hiddenShippingID').value;
 	}
 	else
 	{
 		$('hiddenShippingID').value = j$('#SHIPPINGMETHODID').val();
 		DWREngine._execute(_cfPaymentsFunctions, null,'callapplyShippingMethod',shippingMethodvalue,g_ukey,updateShippingPayment_Result);
 	}
 	
	if(ETA)
		$('shippingETA').value = ETA;
	
}

function updateShippingPayment_Result(result)
{

 	shippingCostResult = result.split("~");
 	shipAmt = shippingCostResult[0].replace(' USD',''); 

 	shipAmtNumeric = shipAmt.replace('$','');
 	shipAmtNumeric = shipAmt.replace(',','');
 	shipAmtNumeric = shipAmtNumeric.split(".");
 	shipAmtNumeric = shipAmtNumeric[0];
 		
	shippingMethodID = shippingCostResult[10];

 	if (shipAmtNumeric == '0' || shipAmtNumeric == '$0')
	{
		if(shippingMethodID == 'NULL')
		{
			if($("shippingShow"))
				$("shippingShow").style.display ='none';
		}
		else
		{
			if($("shippingShow")){
				$("shippingShow").style.display ='';
	    		$("shipping").innerHTML = msg_freeShipping;
	    	}
		}
	}
 	else
 	{
 		if($("shippingShow")){
	 		$("shippingShow").style.display ='';
	    	$("shipping").innerHTML = shipAmt;
	    }	
 	}
 					 			
  if ($("subtotalWTax")) $('subtotalWTax').innerHTML = shippingCostResult[1].replace(' USD','');
  if ($("totalPrice"))  $("totalPrice").innerHTML = shippingCostResult[2].replace(' USD','');
   
   if($("tax1value"))
   {
	    if (document.addEventListener) {
	    	//Mozilla
   			$("tax1valueWrapper").style.display = 'table-row';
   		}else{	
   			//Other
   			$("tax1valueWrapper").style.display = 'block';
   		}
   		
   		$("tax1value").innerHTML =  shippingCostResult[7];
   		
   		taxNumeric = shippingCostResult[7];
   		taxNumeric = taxNumeric.replace('$','');
 		taxNumeric = taxNumeric.replace(',','');
 		taxNumeric = taxNumeric.replace('CAD','');
 		taxNumeric = taxNumeric.replace('USD','');
 		taxNumeric = Number(taxNumeric);
 		
   		
   		if(taxNumeric == 0)
   			$("tax1valueWrapper").style.display = 'none';
   }
   		
   if ($("tax2value"))
   {
	    if (document.addEventListener) {
	    	//Mozilla
   			$("tax2valueWrapper").style.display = 'table-row';
   		}else{
   			$("tax2valueWrapper").style.display = 'block';
   		}
   				   	
   		$("tax2value").innerHTML =  shippingCostResult[8];
   		
   		taxNumeric = shippingCostResult[8];
   		taxNumeric = taxNumeric.replace('$','');
 		taxNumeric = taxNumeric.replace(',','');
 		taxNumeric = taxNumeric.replace('CAD','');
 		taxNumeric = taxNumeric.replace('USD','');
 		taxNumeric = Number(taxNumeric);
 		
   		
   		if(taxNumeric == 0)
   			$("tax2valueWrapper").style.display = 'none';
   }
   
      if ($("surchargeRow"))
   {
   	shippingSurcharge = shippingCostResult[6];
   		if (shippingSurcharge > 0){	
   			$("surchargeRow").style.display =''; 
   		} else {$("surchargeRow").style.display ='none'}
	    $("surchargeAmtRow").innerHTML = '$' + shippingSurcharge;	
   }
    
}

function updateUPSSignatureRequired(shippingMethodValue)
{
    DWREngine._execute(_cfPaymentsFunctions, null,'callgetShippingMethodCourier',updateUPSSignatureRequired_result,shippingMethodValue);
}

function updateUPSSignatureRequired_result(upsSignatureResults)
{
	args = upsSignatureResults.split(",");
   document.getElementById("upsSignatureRequiredBox").style.display = args[0];
   $('upsSignatureRequired').value = args[1];
}

/*
 * amtRows : Amount of line items
 */  
function validateShoppingCart(amtRows,usePickupShippingMethod,zipCodeValidation)
{
	var err = "";
	var shippingMethod = "";
	var country = "";
	var b_oneSizeNotSelected = false;
	var b_oneColorNotSelected = false;
	
	if(!zipCodeValidation)
		zipCodeValidation = false;

	//Check if size of each item is selected
	for(i=1;i<=amtRows;i++)
	{	

		if($('color_'+i) && $('color_'+i).options && b_oneColorNotSelected == false)	
		{
			colorDD = $('color_'+i);

			if(colorDD.options[colorDD.selectedIndex].value == '')
			{
				//Make the error message about size only appear one time.
				b_oneColorNotSelected = true;
				err = err + "<br>" + msg_errorColorNoBreak;
			}					
		}
		
		if($('skuID_'+i) && $('skuID_'+i).options && b_oneSizeNotSelected == false)	
		{
			sizeDD = $('skuID_'+i);

			if(sizeDD.options[sizeDD.selectedIndex].value == '')
			{
				//Make the error message about size only appear one time.
				b_oneSizeNotSelected = true;
				err = err + "<br>" + msg_errorSize;
			}					
		}
		
		// ensure the quantity requested is greater than the minimum order quantity
		if ( $("qty_" + i) && parseInt( $("qty_" + i).value ) < parseInt( $("minimumOrderQty_" + i).value ) ) {
			err += "<br />" + msg_lessThanMinimumQty.replace( /::MINIMUM_ORDER_QTY::/, $("minimumOrderQty_" + i).value ).replace( /::LINE_NO::/, i);
		}
	}

	//Check if country is selected
	if(document.getElementById('country_id')){
		country = document.getElementById('country_id');
		if(country && country.options[country.selectedIndex].value == '')
			err = err + "<br>" + msg_errorCountry;
	}

	//Check if zip code is entered
	if(zipCodeValidation){
		if(j$('#ZipCode').val() == '')
			err = err + "<br>" + msg_enterValidZipCode;		
	}
	
	//Check if shopping method or pickup is selected
	if(usePickupShippingMethod == true){		
		if($('ShopPickupLocation').style.display != "none"){
			pickupMethod = document.getElementById('ShopPickupLocation');
			if(pickupMethod.options[pickupMethod.selectedIndex].value == '')
				err = err + "<br>" + msg_errorPickupMethod;		
		}else{		
			shippingMethod = document.getElementById('ShopShippingMethod');
			if(shippingMethod.options[shippingMethod.selectedIndex].value == '')
				err = err + "<br>" + msg_errorShippingMethod;
		}
	}else{
		shippingMethod = document.getElementById('ShopShippingMethod');
		if(shippingMethod && shippingMethod.options[shippingMethod.selectedIndex].value == '')
			err = err + "<br>" + msg_errorShippingMethod;
	}
	
	if ( err != "" ) {
		showAlert({message:err,cssClass:'alertboxSmall'});
		return;
	}
	
	if ($("chkOnStepCheckOut")){
		if ($("chkOnStepCheckOut").checked){
			var args = {
					method: "validateShoppingCart"
				,	orderID: j$( "#orderID" ).val()
				,   onStepCheckOut : "true"
			};
		} else {
			var args = {
					method: "validateShoppingCart"
				,	orderID: j$( "#orderID" ).val()
			};
		}	
	} else {
		var args = {
				method: "validateShoppingCart"
			,	orderID: j$( "#orderID" ).val()
		};
		
	}	
	
	
	
	j$.post(
			siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
		,	args
		,	validateShoppingCart_result
		,	"json"
	);
}

function validateShoppingCart_result ( result ) {

	if ( result.SUCCESS ) {
		//Show error message or redirect to next page
		document.updateCart.action = g_linkUpdateCart;
		if ($("chkOnStepCheckOut")){
			if ($("chkOnStepCheckOut").checked){
				document.updateCart.nextPage.value = g_linkOneStepCheckoutLocation;
			} else {
				document.updateCart.nextPage.value = g_linkCheckoutLocation;
			}	
		} else {
			document.updateCart.nextPage.value = g_linkCheckoutLocation;
		}	
		document.updateCart.submit();
		//window.location.href = g_linkCheckoutLocation;
	} else {
	
		var showMessage = "";
		
		for ( var i=0; i < result.ERRORS.length; i++ ) {
			pNode = result.ERRORS[ i ];
			
			switch ( pNode.TYPE ) {
				case "MULTIPLE_MISMATCH":
					showMessage += msg_personalisableMultipleMismatch.replace( "::MULTIPLE_QUANTITY::", pNode.MULTIPLE_QUANTITY ).replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "MINIMUM_NOT_ATTAINED":
					showMessage += msg_personalisableMinimumNotAttained.replace( "::MINIMUM_QUANTITY::", pNode.MINIMUM_QUANTITY ).replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "CATEGORY_MINIMUM_NOT_ATTAINED":
					showMessage += msg_personalisableCategoryMinimumNotAttained.replace( "::MINIMUM_QUANTITY::", pNode.MINIMUM_QUANTITY ).replace( "::DESCRIPTION::", pNode.CATEGORY ) + "<br />";
					break;
				case "ITEM_NOT_PERSONALISED":
					showMessage += msg_itemNotPersonalised.replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "PERSONALISATION_MULTIPLE_MISMATCH":
					showMessage += msg_itemPersonalisationMultipleMismatch.replace( "::MULTIPLE_QUANTITY::", pNode.MULTIPLE_QUANTITY ).replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
			}
		}
		
		showMessage = "<strong>" + showMessage + "</strong>";
		
		showAlert({message:showMessage,cssClass:'alertboxSmall'});
		
	}
	
}

function SaveFreeItemMultiorder(arguments){
	if (arguments.orderId > 0 && arguments.skuId != "")
		DWREngine._execute(_cfPaymentsFunctions, null,'callSaveFreeItemMultiorder',arguments.orderId,arguments.line_item_no,arguments.itemId,arguments.skuId,SaveFreeItemMultiorder_Result);
	else if (arguments.orderId > 0)
		alert(msg_freeItemSizeColor);
	else
		alert(j$("#selOrderNav").get(0).options[j$("#selOrderNav").get(0).selectedIndex].text);
		
}

function SaveFreeItemMultiorder_Result(){
	document.location.href = top.location + "&checkDiscount";
}

function saveFreeItemPopup (lineitemnumber,orderid)
{
	temporderid = $('freeItemOrder').value;
	for (var i=0; i < document.updateCartPopUp.freeItemOrder.length; i++)
	   {
	   if (document.updateCartPopUp.freeItemOrder[i].checked)
	      {
	      	var temporderid = document.updateCartPopUp.freeItemOrder[i].value;
	      }
	}
	DWREngine._execute(_cfPaymentsFunctions, null,'callSaveFreitemMultiorder',temporderid,SaveFreitemMultiorder_Result);
}


function SaveFreitemMultiorder_Result(result)
{
	if(result != ''){
		window.location.href = g_linkShoppingCartPayment;
	}
}

function updateWebserviceShippingCost ( orderID, obj ) {
	
	var webserviceShippingCost = obj.value;
	
	var args = {
			method: "updateWebserviceShippingCost"
		,	orderID: orderID
		,	webserviceShippingCost: webserviceShippingCost
	};
	
	j$.post(
			siteUrl + "com/b2c/shoppingcart-proxy.cfc?returnformat=json"
		,	args
		,	function ( result ) {
			if ( !result.SUCCESS ) {
				j$( "#webservice_shipping_cost_" + result.ORDERID.toString() ).val( "" );
					
			}
		}
		,	"json"
	);
	
}

function validateShoppingOptions ()
{
	var err = "";
	var tempShippingMethod = getElementsByName($('updateShippingOptions'),'ShopShippingMethod_');
	for (i=0;i< tempShippingMethod.length;i++) 			
	{
		shippingMethodValue1 = tempShippingMethod[i].options[tempShippingMethod[i].selectedIndex].value;
		if(shippingMethodValue1 == '')
		{
			tempShippingMethod[i].className = 'selectShippingAlert';
			err = '1'
		}
	}
	
	// check delivery dates
	
	
	//Check if shopping method is selected
	//shippingMethod = document.getElementById('ShopShippingMethod');
	//if(shippingMethod.options[shippingMethod.selectedIndex].value == '')
	if(err == '1')
		err = "<br>" + msg_errorShippingMethod;

	//Show error message or redirect to next page
	if(err == ''){		
		//here call a ajax to check the main order get a free item, and check order details to remove lines also
		//in case we have a new free item show a popup to select color size and shipping adrress and then continue     callapplyShippingMethod
		
		j$.post(
				siteUrl + "com/b2c/shoppingCart-proxy.cfc?returnformat=json"
			,	"method=validateShoppingCartMultiOrder"
			,	validateShoppingCartMultiOrder_result
			,	"json"
		);
		
		// DWREngine._execute(_cfPaymentsFunctions, null,'callCheckMultiOrderNewPromotions',CheckMultiOrderNewPromotions_Result);
		
	}else
		showAlert({message:err,cssClass:'alertboxSmall'});	
}

function validateShoppingCartMultiOrder_result(result)
{
	
	var showMessage = "";
	var pNode, multipleXMLMsg, minimumXMLMsg;
	
	if ( !result.SUCCESS ) {
		for ( var i=0; i < result.ERRORS.length; i++ ) {
			pNode = result.ERRORS[ i ];
			
			multipleXMLMsg = msg_personalisableMultipleMismatch;
			minimumXMLMsg = msg_personalisableMinimumNotAttained;
			
			switch ( pNode.TYPE ) {
				case "MULTIPLE_MISMATCH":
					showMessage += msg_personalisableMultipleMismatch.replace( "::MULTIPLE_QUANTITY::", pNode.MULTIPLE_QUANTITY ).replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "MINIMUM_NOT_ATTAINED":
					showMessage += msg_personalisableMinimumNotAttained.replace( "::MINIMUM_QUANTITY::", pNode.MINIMUM_QUANTITY ).replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "CATEGORY_MINIMUM_NOT_ATTAINED":
					showMessage += msg_personalisableCategoryMinimumNotAttained.replace( "::MINIMUM_QUANTITY::", pNode.MINIMUM_QUANTITY ).replace( "::DESCRIPTION::", pNode.CATEGORY ) + "<br />";
					break;
				case "ITEM_NOT_PERSONALISED":
					showMessage += msg_itemNotPersonalised.replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "PERSONALISATION_MULTIPLE_MISMATCH":
					showMessage += msg_itemPersonalisationMultipleMismatch.replace( "::MULTIPLE_QUANTITY::", pNode.MULTIPLE_QUANTITY ).replace( "::DESCRIPTION::", pNode.DESCRIPTION ) + "<br />";
					break;
				case "EMPTY_CART":
					showMessage += msg_emptyCart + "<br />";
					break;
			}
		}
	}
	
	if ( showMessage != "" ) {
		showAlert({message:showMessage,closeBText:'x',cssClass:'alertboxSmall'});
		return false;
	}

	if(result.NEWITEMMESSAGE == 'true'){
	    // show pop up to select size and color for free item and asigned to one shipping address
		showAlert({g_linkfornewitempopup:url,cssClass:'productDetailsWindow'});
	} else {
		window.location.href = g_linkShoppingCartPayment;
	}
}



function validateShoppingCartPayment(id,row)	
{

	var vPaymentMethodSelected = getPaymentMethodSelected();
	var err = '';
	if($('gotoReview')){
		$('gotoReview').disabled = true;
	}
	if (vPaymentMethodSelected == '' && $("totalPrice").innerHTML != "$0.00") {
		err = msg_paymentMethodNotSelected;
	}
	
	for(i=1;i<=row;i++)
	{
		if($('size_'+i)!=null) {
			sizeDD = $('size_'+i);
			sizeDDValue = sizeDD.value;
			
			if(sizeDDValue == '')
			{
				err = msg_errorSize;
				break;
			}
		}
	}
	for(i=1;i<=row;i++)
	{
		if($('sizeID')!=null) {
			sizeDD = $('sizeID');
			sizeDDValue = sizeDD.value;
			
			if(sizeDDValue == '')
			{
				err = msg_errorSize;
				break;
			}
		}
	}
	
	if($('SHIPPINGMETHODID')){
		if($('SHIPPINGMETHODID').value == '')
			err = msg_errorShippingMethod;
	}
	if (vPaymentMethodSelected == 'radioPaymentPO'){
		if ($('poNumber').value.length == 0) {
			err = msg_POMethodNeedPONumber;
		}
	}
	
	//FENG verify checkbox is checked else set err variable with message (XML)
	if ($('acceptAgreement')){
		if ($('acceptAgreement').checked != true)
			err = msg_errorCheckAgreement;
	}	
	
	if (err ==''){
		$(id).submit();
	} else {
		showAlert({message:err,cssClass:'alertboxSmall'});
		$('gotoReview').disabled = false;
	}
}

function validateShoppingCartPaymentNoprices(id,row)	
{

	var err = '';
	$('gotoReview').disabled = true;

	
	for(i=1;i<=row;i++)
	{
		if($('size_'+i)!=null) {
			sizeDD = $('size_'+i);
			sizeDDValue = sizeDD.value;
			
			if(sizeDDValue == '')
			{
				err = msg_errorSize;
				break;
			}
		}
	}
	for(i=1;i<=row;i++)
	{
		if($('sizeID')!=null) {
			sizeDD = $('sizeID');
			sizeDDValue = sizeDD.value;
			
			if(sizeDDValue == '')
			{
				err = msg_errorSize;
				break;
			}
		}
	}
	
	if($('SHIPPINGMETHODID')){
		if($('SHIPPINGMETHODID').value == '')
			err = msg_errorShippingMethod;
	}
	
	//FENG verify checkbox is checked else set err variable with message (XML)
	if ($('acceptAgreement')){
		if ($('acceptAgreement').checked != true)
			err = msg_errorCheckAgreement;
	}	
	
	if (err ==''){
		$(id).submit();
	} else {
		showAlert({message:err,cssClass:'alertboxSmall'});
		$('gotoReview').disabled = false;
	}
}


// this function are for select color and size for free item in a popup
function colorOnChange1(storeID,itemID,colorID,lang,currentRow)
{
 	g_currentRow = currentRow;
 	DWREngine._execute(_cfShoppingCartFunctions, null,'callitemSizeByColor',storeID,itemID,colorID,lang,colorOnChange_Result1);
}

function colorOnChange_Result1(result)
{
 	if ((g_currentRow == null) || (g_currentRow == 'undefined')) {
 		sizeDD = $('sizeID');
 	}else {
 		sizeDD = $('popUpskuID_'+g_currentRow);
 	}
 	
 	sizeDD.options.length = 1;
 	sizeDD.options[0] =  new Option(msg_selectSize,'');
 	
 	
 	for (i=0;i < result.length;i++)
 	{
 		sizeDD.options[i+1] = new Option(result[i]['SIZE_DESCRIPTION'],result[i]['SKU_ID']);
 		sizeDD.options[i+1].id = result[i]['SIZE_DESCRIPTION'];
 	}
 	
}

function sizeOnchangedShoppingCartPopUp(orderId,oldSkuId,NewSkuId,row,itemDesc,lineItemNumber,ukey)
{	
	g_ukey = ukey;
	if (NewSkuId != '')
 	{
 		//check if size changed is not an existing size in shopping cart for same item, else merge		 		
 		if(!(checkExisting(NewSkuId,row,itemDesc)))
 		{		 		
		 	g_oldSizeSelection = $(oldSkuId).value + '|' + row + '|' + oldSkuId;
		 	g_currentRow = row;
		 	qty=eval($('qtypopup_'+''+row));
		 	qty=qty.value;
		 	skuIDD=eval($('skuID_'+''+row));
		 	skuIDD.value = NewSkuId;
		 	oldSKUObj = document.getElementById(oldSkuId)
		 	oldSkuId = oldSKUObj.value;
		 	sku_id_row = 'popUpskuID_'+row
		 	oldSKUObj.value = NewSkuId;
		 	document.getElementById('oldpopUpskuID_'+''+row).value=NewSkuId;
		 	DWREngine._execute(_cfPaymentsFunctions, null,'callupdateOrderDetailsSKU',g_ukey,orderId,oldSkuId,NewSkuId,qty,row,lineItemNumber,sizeOnchangedShoppingCartPopUp_Result);											
 		}
 	}
}
 		
function sizeOnchangedShoppingCartPopUp_Result(result)
{	
//dummy function
}

function createSessionColor(url,color,dimension,skuid){
 	DWREngine._execute(_cfShoppingCartFunctions, null,'createSessionColorItemVariblale',url,color,dimension,skuid,createSessionColor_Result);

}

function createSessionColor_Result(r){
window.location = r;
}

function changeCharity(obj){
	if(!obj){
		DWREngine._execute(_cfPaymentsFunctions, null,'getRoundUpAmount',changeCharity_result);
	}else if(obj.value != "" && $('donation_amount').value == ''){
		DWREngine._execute(_cfPaymentsFunctions, null,'getRoundUpAmount',changeCharity_result);
	}
}

function changeCharity_result(result){
	$('donation_amount').value = result;
}

function updateTotalCharity(){
	var charityId = j$('#change-roundup input:radio:checked').val();
	var donationAmount = jQuery.trim($('donation_amount').value);
	
	if(charityId != ""){
		DWREngine._execute(_cfPaymentsFunctions, null,'setRoundUpCharity',charityId,donationAmount,0,updateTotalCharity_result);
	}else{
		DWREngine._execute(_cfPaymentsFunctions, null,'setRoundUpCharity',charityId,donationAmount,1,updateTotalCharity_result);
	}
}

function updateTotalCharity_result(result){
	var resultDonation = result.split('~');
	
	if( resultDonation[0] == "0" ){
		alert(resultDonation[1]);
	}else{
		setPaymentMethod();
	}
}

function narrowShipppingMethod (countryId, postalCode) {
	j$('#cartShippingDropdown').addClass('opened');
 	DWREngine._execute(_cfPaymentsFunctions, null,'callgetShippingMethodByCountryAndPostalCode',countryId,postalCode,refreshShippingMethodList_Result);
}


function refreshShippingMethodList_Result(result) {
	methodStore = new Array();
	
	var myShippingMethodSelectBox = "";
	var methodIsSelected = false;
	
	//array of the returned shipping methods
	shippingResult = result.split("~");
	
	myShippingMethodList = $("shippingMethodsCtn"); 	
	
	//current selected shipping method
	previousSelected = document.getElementById("selectedShippingMethodName").value;
	
	//Delete all the previous shipping methods options
	childs =  myShippingMethodList.childNodes;
	
	while (childs.length > 0) {
		myShippingMethodList.removeChild(childs[0]);
	}
	
	//Construction of the items of the list ul/li
	for (i=0; i < shippingResult.length-1; i++) {
		
		shippingMethodElem = shippingResult[i];
		shippingMethodProperties = shippingMethodElem.split("|"); 

		//Store the shipping method as an object in the array
		shipMeth = new Object();
		shipMeth.id = shippingMethodProperties[1];
		shipMeth.name = shippingMethodProperties[0];
		shipMeth.coast = shippingMethodProperties[2];
		
		methodStore.push(shipMeth);
		
		//Creation of the li element
		elemLI = document.createElement("li");
		myShippingMethodList.appendChild(elemLI);
		
		//Creation of the input radio
		elemRadioButton = document.createElement("input");
		elemRadioButton.type = "radio";
		elemRadioButton.id = "shippingMethod" + shippingMethodProperties[1];
		elemRadioButton.value = shippingMethodProperties[1];
		elemRadioButton.name = "selectedShippingMethod";
		if (previousSelected == shippingMethodProperties[0]) {
			elemRadioButton.checked = true;
			document.getElementById("selectedShippingMethodId").value = shippingMethodProperties[1];
			methodIsSelected = true;
		}
		else {
			elemRadioButton.checked = false;
		}
		elemLI.appendChild(elemRadioButton);
		//elemRadioButton.addEventListener('click', setShippingMethodValue, false);
		
		if (elemRadioButton.addEventListener){  
			elemRadioButton.addEventListener('click', setShippingMethodValue, false);   
		} else if (elemRadioButton.attachEvent){  
			elemRadioButton.attachEvent('onclick', setShippingMethodValue);  
		}  

		//Creation of the text of the li element
		liLabel = document.createElement("label");
		liLabel.id = "liLabel" + shippingMethodProperties[1];
		liLabelText = document.createTextNode(shippingMethodProperties[0]);
		liLabel.appendChild(liLabelText);
		//liLabel.for = "shippingMethod" + shippingMethodProperties[1];
		liLabel.setAttribute("for", "shippingMethod" + shippingMethodProperties[1]);
		elemLI.appendChild(liLabel);
		
		//correspondance between the method id and its name
		corrShipMeth = document.createElement("input");
		corrShipMeth.type = "hidden";
		corrShipMeth.id = "corrShipMeth" + shippingMethodProperties[1];
		corrShipMeth.value = shippingMethodProperties[0];
		elemLI.appendChild(corrShipMeth);
		
		//Coast of the shipping method
		spanCoast = document.createElement("span");
		spanCoast.className = "price";
		if (isNaN(shippingMethodProperties[2])) {
			coast = "$0.00"
		}
		else {
			coast = document.createTextNode("$" + shippingMethodProperties[2]);
		}
		
		spanCoast.appendChild(coast);
		elemLI.appendChild(spanCoast);
		
		//If a shipping method is selectionned refrsh the values
		if ( !methodIsSelected) {
			document.getElementById("selectedShippingMethodId").value = "";
			document.getElementById("selectedShippingMethodName").value = "";
		}
	}
	
}

function setShippingMethodValue() {
	//Save the selected shipping option
	document.getElementById("selectedShippingMethodName").value = document.getElementById("corrShipMeth" + this.value).value;
	document.getElementById("selectedShippingMethodId").value = this.value;
	callCheckDiscount('false');
}


function callCheckDiscount(refreshPage) {
	hideButton(true);
	g_numberLineItems = document.getElementById("skuCount").value; 
 	g_refreshPage = refreshPage;
 	if($('Discounts')){
 		discountcode = $('Discounts').value;
 	} else {
 		discountcode = '';
 	}	
	DWREngine._execute(_cfPaymentsFunctions, null,'callapplyDiscountCode',discountcode,g_ukey,callCheckDiscount_Result);	
}

function callCheckDiscount_Result(result) {
	var discountHaveFreeItem = false;
 	discountResult = result.split("~");
 	if(discountResult[0]=='invalid') {	
 		//Discount is not valid
 		if($("discountShow")) { 
 			$("discountShow").style.display ='none'; 
 		}
 		
 		$("discountAmount").innerHTML = '';
 		
 		temp = discountResult[2].replace('$','');
	    
 		if ($("totalPrice")) {
 			$("totalPrice").innerHTML = '$'+temp;
 		}
 		
	    if(g_refreshPage == true){
		    //Refresh the page
		    if(g_currentShoppingCartPage == "shoppingCartPayment")
	 			refreshPaymentPage("discountNotValid");
	 		else
	 			refreshShoppingCartPage("discountNotValid");
	    } else {
	 		if($("Discounts")) { $("Discounts").value = ''; }
	    	hideButton(false);
	    }
	    
 	} else {
 		
 		//Discount is valid
 		
 		if(g_refreshPage == true){
 			//Refresh the page
 			if(g_currentShoppingCartPage == "shoppingCartPayment")
 				refreshPaymentPage("");
 			else
 				refreshShoppingCartPage("");
 		}else{

		 	if (discountResult[0]=='valid')
	        {
	        	//Discount type is free item
	        	if(discountResult[3]==5)
	            {
	            	discountHaveFreeItem = true;
	            	
	            	if($("discountShow"))
	            		$("discountShow").style.display ='none';
	            	
	            	if ($("discountAmount")) $("discountAmount").innerHTML = '';
	            	
	 				temp = discountResult[2].replace('$','');
		    		if ($("totalPrice")) $("totalPrice").innerHTML = '$'+temp;
	        		
	        		DWREngine._execute(_cfPaymentsFunctions, null,'callfreeItemDiscount',g_actualLang,checkDiscountFreeItemdiscount_Result);
	            }
	        	else
	        	{
	        		//Free item indicator 
	        		if(discountResult[7]=='Y') {
	        			discountHaveFreeItem = true;
        				DWREngine._execute(_cfPaymentsFunctions, null,'callfreeItemDiscount',g_actualLang,checkDiscountFreeItemdiscount_Result);
	        		}
	        		
	        		if($("discountShow"))
        				$("discountShow").style.display ='';
		        	
		        	if($("discountAmount")!=null) 
		        		$("discountAmount").innerHTML = discountResult[1];
		        	
		        	temp = discountResult[2].replace('$','') - discountResult[4].replace('$','') - discountResult[5].replace('$','');
			 		
			 		if ($("totalPrice")) $("totalPrice").innerHTML = '$'+temp.toFixed(2);
	        	}	
	        }
		 	callRefreshShippingMethod();
 		}			 	
 	}
}


function callRefreshShippingMethod() {
	if ( !$("SHIPPINGMETHODID") && !$("ShopShippingMethod") ) {
		hideButton( false );
		return false;
	}
	
	if(document.getElementById('country_id')){
 		countryID = $('country_id').value;   
	}else{
		countryID = 'US';	
	}
 	DWREngine._execute(_cfPaymentsFunctions, null,'callgetShippingMethod',countryID,callRefreshShippingMethod_Result);
}

function callRefreshShippingMethod_Result(result)
{
	var myShippingMethodSelectBox = "";
	
	shippingResult = result.split("~");
	
	if($("SHIPPINGMETHODID")){
		//Payment page
		myShippingMethodSelectBox = $("SHIPPINGMETHODID");
	}else{
		//Shopping cart page
		myShippingMethodSelectBox = $("selectedShippingMethodId"); 	
 	}	
	
	shippingMethodvalue = myShippingMethodSelectBox.value;
	
	if($("SHIPPINGMETHODID")){
		//Payment page
		updateShippingPayment(shippingMethodvalue);
	}else{
		//Shopping cart page
		UpdateShipping(shippingMethodvalue);			
	}	
	
	if (document.getElementById("ShopShippingMethod"))
	{
	document.getElementById("ShopShippingMethod").disabled = false;
	} else {
		document.getElementById("shippingMethodID").disabled = false;
	}
}

function getShippingMethodsFromZip(zipCode,orderNumber, checkDisplayFrontEndInd, checkDisplayAdminInd, country_id,onlyGiftCard)
{

	// checkDisplayFrontEndInd argument added for admin; make sure that the default is true
	if (checkDisplayFrontEndInd == undefined)
	{
		checkDisplayFrontEndInd = true;
	}
	
	// checkDisplayAdminInd argument added for admin; make sure that the default is false
	if (checkDisplayAdminInd == undefined)
	{
		checkDisplayAdminInd = false;
	}
	
	// country_id added; set default to empty string
	if (country_id == undefined)
	{
		country_id = '';
	}

	var args = {

		//beforeSubmit: function() {alert("beforeSubmit");},
		type		: "post",
		dataType	: "json",
		data		: {zipCode: zipCode, orderNumber: orderNumber, displayFrontEnd: checkDisplayFrontEndInd, checkDisplayAdminInd: checkDisplayAdminInd, country_id: country_id,onlyGiftCard:onlyGiftCard, method: "getShippingMethodsFromZip"},
		url			: siteUrl + "com/b2c/genericproxy.cfc?returnformat=json",
		error		: function(){alert("error");},
		success		: getShippingMethodsFromZip_result
		//,complete		: function() {alert("complete");}
	};


	//$('ShopShippingMethod').disabled = true;

    j$.ajax(args);
			
};	

function getShippingMethodsFromZip_result(data)
{
	var loc = {};
	loc.myOptions = {};
	
	//j$("#shipMethodFieldset").hide();
	
	loc.preselectedValue = j$("#ShopShippingMethod").selectedValues();
		loc.preselectedValue = j$("#shippingMethodID").selectedValues();
	
	j$("#ShopShippingMethod").removeOption(/./);
	j$("#shippingMethodID").removeOption(/./);
	
	if(data.SUCCESS)
	{
		for (i=0; i<data.STRUCTSHIPPINGMETHODS.length; i++) 
		{
			loc.myOptions[data.STRUCTSHIPPINGMETHODS[i].SHIPPING_METHOD_ID] = data.STRUCTSHIPPINGMETHODS[i].DESCRIPTION;
			//j$("#ShopShippingMethod").addOption(data.STRUCTSHIPPINGMETHODS[i].SHIPPING_METHOD_ID, data.STRUCTSHIPPINGMETHODS[i].DESCRIPTION);
		}

		j$("#ShopShippingMethod").addOption(loc.myOptions,false);
		j$("#ShopShippingMethod").selectOptions(loc.preselectedValue);
		j$("#shippingMethodID").addOption(loc.myOptions,false);
		j$("#shippingMethodID").selectOptions(loc.preselectedValue);
		//j$("#shipMethodFieldset").show();
		
		if (document.getElementById("ShopShippingMethod"))
		{
		document.getElementById("ShopShippingMethod").disabled = false;
		} else {
			document.getElementById("shippingMethodID").disabled = false;
		}
	} else {
		countryID = document.getElementById('country_id').value;
		DWREngine._execute(_cfPaymentsFunctions, null,'callgetShippingMethod',countryID,refreshShippingCountry_Result);
	}
	
	
};







