


/**
 * jQuery.pulse
 * Copyright (c) 2008 James Padolsey - jp(at)qd9(dot)co.uk | http://james.padolsey.com / http://enhance.qd-creative.co.uk
 * Dual licensed under MIT and GPL.
 * Date: 05/11/08
 *
 * @projectDescription Applies a continual pulse to any element specified
 * http://enhance.qd-creative.co.uk/demos/pulse/
 * Tested successfully with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.5 and Safari 3. on Windows XP.
 *
 * @author James Padolsey
 * @version 1.11
 * 
 * @id jQuery.pulse
 * @id jQuery.recover
 * @id jQuery.fn.pulse
 * @id jQuery.fn.recover
 */
(function($){
    $.fn.recover = function() {
        /* Empty inline styles - i.e. set element back to previous state */
        /* Note, the recovery might not work properly if you had inline styles set before pulse initiation */
        return this.each(function(){$(this).stop().css({backgroundColor:'',color:'',borderLeftColor:'',borderRightColor:'',borderTopColor:'',borderBottomColor:'',opacity:1});});
    }
    $.fn.pulse = function(options){
        var defaultOptions = {
            textColors: [],
            backgroundColors: [],
            borderColors: [],
            opacityPulse: true,
            opacityRange: [],
            speed: 1000,
            duration: false,
            runLength: false
        }, o = $.extend(defaultOptions,options);
        /* Validate custom options */
        if(o.textColors.length===1||o.backgroundColors.length===1||o.borderColors.length===1) {return false;}
        /* Begin: */
        return this.each(function(){
            var $t = $(this), pulseCount=1, pulseLimit = (o.runLength&&o.runLength>0) ? o.runLength*largestArrayLength([o.textColors.length,o.backgroundColors.length,o.borderColors.length,o.opacityRange.length]) : false;
            clearTimeout(recover);
            if(o.duration) {
                setTimeout(recover,o.duration);
            }
            function nudgePulse(textColorIndex,bgColorIndex,borderColorIndex,opacityIndex) {
                if(pulseLimit&&pulseCount===pulseLimit) {
                    return $t.recover();
                }
                pulseCount++;
                /* Initiate color change - on callback continue */
                return $t.animate(getColorsAtIndex(textColorIndex,bgColorIndex,borderColorIndex,opacityIndex),o.speed,function(){
                    /* Callback of each step */
                    nudgePulse(
                        getNextIndex(o.textColors,textColorIndex),
                        getNextIndex(o.backgroundColors,bgColorIndex),
                        getNextIndex(o.borderColors,borderColorIndex),
                        getNextIndex(o.opacityRange,opacityIndex)
                    );
                });
            }
            /* Set CSS to first step (no animation) */
            $t.css(getColorsAtIndex(0,0,0,0));
            /* Then animate to second step */
            nudgePulse(1,1,1,1);
            function getColorsAtIndex(textColorIndex,bgColorIndex,borderColorIndex,opacityIndex) {
                /* Prepare animation object - get's all property names/values from passed indexes */
                var params = {};
                if(o.backgroundColors.length) {
                    params['backgroundColor'] = o.backgroundColors[bgColorIndex];
                }
                if(o.textColors.length) {
                    params['color'] = o.textColors[textColorIndex];
                }
                if(o.borderColors.length) {
                    params['borderLeftColor'] = o.borderColors[borderColorIndex];
                    params['borderRightColor'] = o.borderColors[borderColorIndex];
                    params['borderTopColor'] = o.borderColors[borderColorIndex];
                    params['borderBottomColor'] = o.borderColors[borderColorIndex];
                }
                if(o.opacityPulse&&o.opacityRange.length) {
                    params['opacity'] = o.opacityRange[opacityIndex];
                }
                return params;
            }
            function getNextIndex(property,currentIndex) {
                if (property.length>currentIndex+1) {return currentIndex+1;}
                else {return 0;}
            }
            function largestArrayLength(arrayOfArrays) {
                return Math.max.apply( Math, arrayOfArrays ); 
            }
            function recover() {
                $t.recover();
            }
        });
    }
})(jQuery);
/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function($){

	// We override the animation for all of these color styles
	$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		$.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[$.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = $.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

////////////////////////////////////////////////////////////////////////////////
//*********** JQUERY FORM ******************************************************
////////////////////////////////////////////////////////////////////////////////



/*
 * jQuery Form Plugin
 * version: 2.25 (08-APR-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 

;(function($) {
/*
    Usage Note:
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });

    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    // clean url (don't include hash vaue)
    var url = this.attr('action') || window.location.href;
    url = (url.match(/^([^#]+)/)||[])[1];
    url = url || '';

    options = $.extend({
        url:  url,
        type: this.attr('method') || 'POST' // carlo (dubbio, era GET non POST)
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } );
          }
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) {
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if (options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];

        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }

        var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" src="about:blank" />');
        var io = $io[0];

        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() {
                this.aborted = 1;
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
        }
        if (xhr.aborted)
            return;

        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);

                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
                t ? form.setAttribute('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        var nullCheckFlag = 0;

        function cb() {
            if (cbInvoked++) return;

            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

                if ((doc.body == null || doc.body.innerHTML == '') && !nullCheckFlag) {
                    // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when
                    // the onload callback fires, so we give them a 2nd chance
                    nullCheckFlag = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }

                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
                	v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
    if (b == undefined) b = true;
    return this.each(function() {
        this.disabled = !b;
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/*
 * Traduzione dei messaggi di default per il pugin jQuery validation.
 * Language: IT
 * Traduzione a cura di Davide Falchetto
 * E-mail: d.falchetto@d4solutions.it
 * Web: www.d4solutions.it
 */
if($.validator) 
$.extend($.validator.messages, {
       required: " Campo obbligatorio",
       remote: " Controlla questo campo",
       email: " Inserisci un indirizzo email valido",
       url: " Inserisci un indirizzo web valido",
       date: " Inserisci una data valida",
       dateISO: " Inserisci una data valida (ISO)",
       number: " Inserisci un numero valido",
       digits: " Inserisci solo numeri",
       creditcard: " Inserisci un numero di carta di credito valido",
       equalTo: " Il valore non corrisponde",
       accept: " Inserisci un valore con un&apos;estensione valida",
       maxlength: $.format(" Non inserire pi&ugrave; di {0} caratteri"),
       minlength: $.format(" Inserisci almeno {0} caratteri"),
       rangelength: $.format(" Inserisci un valore compreso tra {0} e {1} caratteri"),
       range: $.format(" Inserisci un valore compreso tra {0} e {1}"),
       max: $.format(" Inserisci un valore minore o uguale a {0}"),
       min: $.format(" Inserisci un valore maggiore o uguale a {0}")
});


//IMPLEMENTAZIONE TEMP

jQuery.validator.addMethod("allurl", function(value) {
	// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
	return /^(https?|ftp|mms|rtsp|rtmp|pna|pnm):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}, ' Inserisci un url valido.');


(function($){

////////////////////////////////////////////////////////////////////////////////
//========== MYAJAXFORM ==========================================================
////////////////////////////////////////////////////////////////////////////////
	
var MyAjaxForm = {
	build : function(options){
		var _options = $.extend({}, options);
		var _metadata = {};
		
		return this.each(function(){
			
			$("form.ajaxform", this).each(function(){
				if($.metadata)
					_metadata = $(this).metadata();
					
				
				var that = this;
				var _validate = $(this).is(".validate");
				/*
				var _file = $(this).attr('enctype') == 'multipart/form-data';
				if(_file){
					//this.action = '/lib/files.php';
					$(this).ajaxForm({			
						success: function(data) {
							console.log(data);	
						}
					});
				}
					
				if(_file)
					return;
				*/
				_options = $.extend(_options, _metadata);
					
				$(this).submit(function() { 
					
					
	        		//_options.target = '#ajaxform-target';
	        		//var _file = $(this).attr('enctype') == 'multipart/form-data';
					//console.log(_file);
					//if (_file) {
					//	_options.dataType = 'xml';
					//}else {
					_options.dataType = 'json';
					//}
					//console.log(_options.dataType);
					_options.success = function(responseText, statusText){
						 MyAjaxForm.response(that.id,responseText, statusText);
	        		};
	        		//console.log($(this).validate().form());
	        		if(_validate && !$(this).validate().form())
						return false;
	        		        		
	        		if(!_validate || (_validate && $(this).validate().form())){
	        			$(this).ajaxSubmit(_options); 
	 	       			return false;
					}
	    		});	
			});
			
		});
		 
	},
	response : function(id, response, status){
		switch(id){
			case "frm_mappe":
				MyAjaxForm.form_mappe(response);
				MyAjaxForm.close();
			break;
			
			case "frm_immagini":
				MyAjaxForm.form_immagini(response);
				MyAjaxForm.close();
			break;

			case "frm_immagini_commento":
				MyAjaxForm.form_immagini_commento(response);
				MyAjaxForm.close();
			break;
			
			case "frm_video":
				MyAjaxForm.form_video(response);
				MyAjaxForm.close();
			break;

			case "frm_video_commento":
				MyAjaxForm.form_video_commento(response);
				MyAjaxForm.close();
			break;

			case "frm_link":
				MyAjaxForm.form_link(response);
				MyAjaxForm.close();
			break;

			case "frm_link_commento":
				MyAjaxForm.form_link_commento(response);
				MyAjaxForm.close();
			break;
			
			case "frm_modifica":
				if(response['esito'] == 1) {
					var _form = $("#frm_modifica");
					_form.hide();
					//leggi i dati dal form
					var _nome = $("#nome",_form).val();
					var _indirizzo = $("#indirizzo",_form).text();
					var _comune = $("#comune",_form).text();
					var _provincia = $("#provincia",_form).text();
					var _certa_al = $("#certa_al",_form).val();
					var _certa_dal = $("#certa_dal",_form).val();
					var _dal = $("#attivo_dal",_form).val();
					var _al = $("#attivo_al",_form).val();
					if (_al == ''){
						_al = 'attivo';
					}

					var open_par_certa_al = '';
					var close_par_certa_al = '';
					if (_certa_al==1) {
						var open_par_certa_al = '(';
						var close_par_certa_al = ')';
					}
					var open_par_certa_dal = '';
					var close_par_certa_dal = '';
					if (_certa_dal==1) {
						var open_par_certa_dal = '(';
						var close_par_certa_dal = ')';
					}

					var _settore = $("#id_settore option:selected",_form).text();
					_settore = $.trim(_settore);
					var _descrizione = $("#descrizione",_form).val();
					
					//copio i dati nel div di riepilogo
					var _response = $("#form_response");
					$("#response_nome", _response).text(_nome);
					$("#response_indirizzo", _response).text(_indirizzo);
					$("#response_comune", _response).text(_comune);
					$("#response_provincia_nome", _response).text(_provincia);
					$("#response_attivo_dal", _response).text(open_par_certa_dal+_dal+close_par_certa_dal);
					$("#response_attivo_al", _response).text(open_par_certa_al+_al+close_par_certa_al);
					$("#response_id_settore", _response).empty().text(_settore);
					$("#response_descrizione", _response).text(_descrizione);

					// nascnde comune se uguale ad indirizzo
					var _cap = _indirizzo.substring(0,5);
					var espressione_cap = RegExp("[0-9]");
					
					if (espressione_cap.test(_cap)) {
						var _indirizzo = _indirizzo.substring(6);
					}
					var _len_ind = _indirizzo.length;
					var _indirizzo = _indirizzo.substring(0,_len_ind);
					
					if (_indirizzo == _comune) {
						$("#response_comune", _response).hide();
					} 
					
					var _azione = jQuery('input#azione').val();
			
					if(_azione=='inserisci') {
						$("#tabs").find('#divlink_modifica').hide();
						$("#tabs").find('#divlink_inserisci').show();
					} else {
						$("#tabs").find('#divlink_modifica').show();
						$("#tabs").find('#divlink_inserisci').hide();
					}
			
					_response.show();
					map.closeInfoWindow();
				}

			break;

			case "frm_commento":
				if(response['esito'] == 1) {
					var _form = $("#frm_commento");
					_form.hide();
					//leggi i dati dal form
					var _nome = $("#name",_form).text();
					var _periodo = $("#periodo",_form).text();
					var _autore = $("#autore",_form).text();
					var _settore = $("#settore",_form).text();
					var _testo = $("#testo",_form).val();
					
					_settore = $.trim(_settore);
					
					//copio i dati nel div di riepilogo
					var _response = $("#form_response");
					$("#response_name", _response).text(_nome);
					$("#response_periodo", _response).text(_periodo);
					$("#response_autore", _response).text(_autore);
					$("#response_settore", _response).text(_settore);
					$("#response_testo", _response).text(_testo)
					
					$("#tabs").find('.divlink').show();
					_response.show();
					map.closeInfoWindow();
				}

			break;
			
			default:
				if(response['esito'] == 1) {
					var _form = $("#frm_modifica");
					_form.hide();
					//leggi i dati dal form
					var _nome = $("#nome",_form).val();
					var _indirizzo = $("#indirizzo",_form).text();
					var _comune = $("#comune",_form).text();
					var _provincia = $("#provincia",_form).text();
					var _certa_al = $("#certa_al",_form).val();
					var _certa_dal = $("#certa_dal",_form).val();
					var _dal = $("#attivo_dal",_form).val();
					var _al = $("#attivo_al",_form).val();
					if (_al == ''){
						_al = 'attivo';
					}

					var open_par_certa_al = '';
					var close_par_certa_al = '';
					if (_certa_al==1) {
						var open_par_certa_al = '(';
						var close_par_certa_al = ')';
					}
					var open_par_certa_dal = '';
					var close_par_certa_dal = '';
					if (_certa_dal==1) {
						var open_par_certa_dal = '(';
						var close_par_certa_dal = ')';
					}					
					var _settore = $("#id_settore option:selected",_form).text();
					_settore = $.trim(_settore);
					var _descrizione = $("#descrizione",_form).val();
					
					
					//copio i dati nel div di riepilogo
					var _response = $("#form_response");
					$("#response_nome", _response).text(_nome);
					$("#response_indirizzo", _response).text(_indirizzo);
					$("#response_comune", _response).text(_comune);
					$("#response_provincia_nome", _response).text(_provincia);
					$("#response_attivo_dal", _response).text(open_par_certa_dal+_dal+close_par_certa_dal);
					$("#response_attivo_al", _response).text(open_par_certa_al+_al+close_par_certa_al);
					$("#response_id_settore", _response).empty().text(_settore);
					$("#response_descrizione", _response).text(_descrizione);
					
					// nascnde comune se uguale ad indirizzo
					var _cap = _indirizzo.substring(0,5);
					var espressione_cap = RegExp("[0-9]");
					
					if (espressione_cap.test(_cap)) {
						var _indirizzo = _indirizzo.substring(6);
					}
					var _len_ind = _indirizzo.length;
					var _indirizzo = _indirizzo.substring(0,_len_ind);
					
					if (_indirizzo == _comune) {
						$("#response_comune", _response).hide();
					}
										
					_response.show();
					map.closeInfoWindow();
				}
			break;
		}
	},
	close : function(){
		 $("#ahah").remove();
         $(".ui-dialog").remove();
         $("#mydialog-target").remove();
	},
	pulse : {
		backgroundColors: ['#222222','#C1330F'],
		opacityRange: [0.4,0.9],
		speed: 1000,
		duration : 5000
	},
	form_mappe : function(response){
		var _id = response['id'];
		var _id_stabilimento = response['id_stabilimento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_mappe_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_allegato('+_id_stabilimento+',\'mappe\','+_id+')" class="linkarancio">elimina</a></p>';
		
		$('#elenco_oggetti_mappe').append(_html);
		
		$('#cont_mappe').trigger("click");
		
		var _num = parseInt($('#countmappe').text());
		$('#countmappe').text(++_num);
		
		$('.tr_mappe_'+_id).pulse(MyAjaxForm.pulse);
	},
	form_immagini : function(response){
		
		var _id = response['id'];
		var _id_stabilimento = response['id_stabilimento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_immagini_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_immagine_stabilimento('+_id_stabilimento+',\'immagini\','+_id+')" class="linkarancio">elimina</a></p>';
		$('#elenco_oggetti_immagini').append(_html);
		
		$('#cont_immagini').trigger("click");
		
		var _num = parseInt($('#countimmagini').text());
		$('#countimmagini').text(++_num);
		
		
		$('.tr_immagini_'+_id).pulse(MyAjaxForm.pulse);
		
	},
	form_immagini_commento : function(response){
		var _id = response['id'];
		var _id_commento = response['id_commento'];
		var _id_stabilimento = response['id_stabilimento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_immagini_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_immagine_commento(\'immagini\','+ _id_stabilimento+','+ _id_commento+','+_id+')" class="linkarancio">elimina</a></p>';
		$('#elenco_oggetti_immagini').append(_html);
		
		$('#cont_immagini').trigger("click");
		
		var _num = parseInt($('#countimmagini').text());
		$('#countimmagini').text(++_num);
		
		
		$('.tr_immagini_'+_id).pulse(MyAjaxForm.pulse);
		
	},
	form_video : function(response){
		var _id = response['id'];
		var _id_stabilimento = response['id_stabilimento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_video_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_allegato'+_id_stabilimento+',\'video\','+_id+')" class="linkarancio">elimina</a></p>';
		$('#elenco_oggetti_video').append(_html);
		
		$('#cont_video').trigger("click");
		
		var _num = parseInt($('#countvideo').text());
		$('#countvideo').text(++_num);
		
		
		$('.tr_video_'+_id).pulse(MyAjaxForm.pulse);
		
	},
	form_video_commento : function(response){
		var _id = response['id'];
		var _id_stabilimento = response['id_stabilimento'];
		var _id_commento = response['id_commento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_video_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_allegato_commento(\'video\','+_id+','+_id_commento+')" class="linkarancio">elimina</a></p>';
		$('#elenco_oggetti_video').append(_html);
		
		$('#cont_video').trigger("click");
		
		var _num = parseInt($('#countvideo').text());
		$('#countvideo').text(++_num);
		
		
		$('.tr_video_'+_id).pulse(MyAjaxForm.pulse);
		
	},

	form_link : function(response){
		var _id = response['id'];
		var _id_stabilimento = response['id_stabilimento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_link_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_allegato('+_id_stabilimento+',\'link\','+_id+')" class="linkarancio">elimina</a></p>';
		$('#elenco_oggetti_link').append(_html);
		
		$('#cont_link').trigger("click");
		
		var _num = parseInt($('#countlink').text());
		$('#countlink').text(++_num);
		
		
		$('.tr_link_'+_id).pulse(MyAjaxForm.pulse);
		
	},
	form_link_commento : function(response){
		var _id = response['id'];
		var _id_commento = response['id_commento'];
		var _id_stabilimento = response['id_stabilimento'];
		var _descrizione = response['descrizione'];
		var _html = '<p class="tr_video_'+_id+'"><a href="javascript:void(0);" class="txtFFF" >'+_descrizione+'</a><span class="testonascosto">&nbsp;|&nbsp;</span><a href="javascript:void(0);" onclick="Stabilimento.elimina_allegato_commento(\'video\','+_id+','+_id_commento+')" class="linkarancio">elimina</a></p>';
		$('#elenco_oggetti_link').append(_html);
		
		$('#cont_link').trigger("click");
		
		var _num = parseInt($('#countlink').text());
		$('#countlink').text(++_num);
		
		
		$('.tr_link_'+_id).pulse(MyAjaxForm.pulse);
		
	}		
};	
	
$.fn.myajaxform = MyAjaxForm.build;

////////////////////////////////////////////////////////////////////////////////
//*********** AUTOLOAD *********************************************************
////////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){
	$("body").myajaxform();
});
	
})(jQuery);


(function($){


var MyValidate = function(){
	return this.each(function(){
		$("form.validate", this).each(function(){
			var _form = this;
			//console.log(this)
			var _metadata = {};
			if($.metadata)
				_metadata = $(this).metadata();
			
			if($.fn.validate){
				var _validator = $(this).validate(_metadata);
			}
			
		});
	});
};	

$.fn.myvalidate = MyValidate;
	
$(document).ready(function(){

	$('body').myvalidate();
	
	

});
	
})(jQuery);


//MYDIALOG
(function($){

var MyDialog = function(){
    return this.each(function(){
    
        var that = this;
        var _options = {};
		var _target = this.href.split("#").slice(1);//.replace("#","");
		
        
        $(this).click(function(){
			function _close(ev){
				//console.log(ev)
				var _target = ev.target || ev.srcElement;
				//$(_target).remove();
				//console.log(_target)
				//return;
				$("#ahah").remove();
				$(".ui-dialog").remove();
				$("#mydialog-target").remove();
			};

            _options.close = _close;
            _options.modal = true;
			_options.buttons = {
				'conferma' : function(){
					$("#"+_target).find("form").submit();
				},
				'annulla' : _close
			};

			var _t = $("#"+_target);
			_t.show().dialog(_options)
			
			_t.find("input:text, input:file").val("");
			_t.find("#carta_url").val("http://");
			_t.find("#link_url").val("http://");
			_t.find("#video_url").val("http://");
			
            return false;
        });
    });
}

	
$.fn.mydialog = MyDialog;

	
$(document).ready(function(){

	$('a.mydialog').mydialog();
	$('#elimina').mydialog();

});
	
})(jQuery);

//ready per il tab iniettato
(function($){

var AttachdialogReady = function(){
    $(this)
    .myvalidate()
    .myajaxform()
    .find('a.mydialog').mydialog()
    
    //anno di chiusura
    if($('#ancoraSI').is(":checked"))
	$('.tr_chiusura').hide();
    
    $('#ancoraNO').change(function(){
		if($(this).is(":checked")) 
			$('.tr_chiusura').show();
    });
    $('#ancoraSI').change(function(){
		if($(this).is(":checked")){
	    	$('.tr_chiusura').hide();
	    	$('.tr_chiusura').find("input:text").val("");
		}
    });

	$(".cont_oggetto").each(function(nr){
		var that = this;
		var _children = $('.elenco_oggetti > p');
		var _has_child = _children.length > 0;

		if(_has_child){

		}
		$(that).bind("close", function(){
			$(that).find("div:eq(0)").removeClass("aperto").addClass("chiuso");
			$(that).find(".elenco_oggetti").hide();
		});
		$(that).bind("open", function(){
			$(that).find("div:eq(0)").removeClass("chiuso").addClass("aperto");
			$(that).find(".elenco_oggetti").show();
		});
		//chiudi
		$('div:eq(0) > a:eq(0)',that).click(function(){
			$(".cont_oggetto:not("+nr+")").trigger("close");
			$(that).trigger("open");
			return false;
		});

		
		
	});
	//chiudi tutti
	$(".cont_oggetto:not(0)").trigger("close");
	//$(".cont_oggetto:eq(0)").trigger("open");

};

	
$.fn.attachdialog = AttachdialogReady;

	
})(jQuery);