$(document).ready(function()
{
    $.fn.formLabels();
	
	$("span[alt], div[alt], img.simpleTip").qtip({
		content: {
	      attr: 'alt'
	   }
	});
	
	$( "#tabs" ).tabs({ cookie: { expires: 30, path: '/' } });
	
	$(".accordion .categoria").each(function() {
		
		if($(this).hasClass('active'))
		{
			$(this).toggleClass('open', true);
			$(this).next().toggleClass('hover', true);
			$(this).next().show();
		}
		toggleMenu(this);
		//checkCookie(this);
		$(this).mouseenter(function(){
			$(this).next().toggleClass('hover', true);
		});
		$(this).mouseleave(function(){
			$(this).next().toggleClass('hover', false);
		});
		
		$(this).next().mouseenter(function(){
			$(this).next().toggleClass('hover', true);
		});
		$(this).next().mouseleave(function(){
			$(this).next().toggleClass('hover', false);
		});
	});
	
	$(".accordion a").each(function() {
		$(this).click(function(event){
			event.stopPropagation();
		});
	});

	function checkCookie(id) {
		// check if there is a cookie set for a sub menu 
		// if there is then show the menu
		var cookieName = id.id;
		var c = readCookie(cookieName);
		if(c === 'show') {
			$(id).each(function() {
				$(this).toggleClass('open', true);
				$(this).next().slideDown('fast');
			});
		}
	}
	
	function toggleMenu(id) {
		$(id).click(function() {
			togglePlusMinus(this); 									// toggle the +/- indicators	
			$(this).next().slideToggle("fast"); 		//toggle the menu open or closed
		});
	}
	
	function togglePlusMinus(id) {
		$(id).each(function() {
			if($(this).hasClass('open')) {
				$(this).toggleClass('open', false);
				eraseCookie(this.id);
			} else {
				$(this).toggleClass('open', true);
				createCookie(this.id, 'show', 365);
			}
		});
	}
});

// NON FUNZIONA CON I FILE
/*
var _id = '';

$(document).ready(function() {
 
  $("#addElement").click( 
      function() { 
          ajaxAddField();
       }
    );
 
  $("#removeElement").click(
      function() {
          removeField();
      }
    );
  //Get value of id - integer appended to dynamic form field names and ids
	_id = $("#idNew").val();
  }
);
 

 
// Retrieve new element's html from controller
function ajaxAddField() {
  $.ajax(
    {
      type: "POST",
      url: "http://confettirossi_beta/fotografo/servizi/newfield/format/html",
      data: "id=" + _id,
      success: function(newElement) {
 
        // Insert new element before the Add button
        $("#addElement").parent().before(newElement);
 
        // Increment and store id
        $("#idNew").val(++_id);
      }
    }
  );
}
 
function removeField() {
 
  // Get the last used id
  var lastId = $("#idNew").val() - 1;
 
  // Build the attribute search string.  This will match the last added  dt and dd elements.  
  // Specifically, it matches any element where the id begins with 'newName<int>-'.
  searchString = '*[id^=ajaxFoto' + lastId + '-]';
 
  // Remove the elements that match the search string.
  // con next rimuoviamo il dd
  $(searchString).next().remove()
  // e poi il dt
  $(searchString).remove()
 
  // Decrement and store id
  $("#idNew").val(--_id);
}
*/

//cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date(); 		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) { createCookie(name,"",-1); }

jQuery.cookie = function (key, value, options) {
    
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
       
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

jQuery.JSON = {
		useHasOwn : ({}.hasOwnProperty ? true : false),
		pad : function(n) {
		return n < 10 ? "0" + n : n;
		},
		m : {
		"\b": '\\b',
		"\t": '\\t',
		"\n": '\\n',
		"\f": '\\f',
		"\r": '\\r',
		'"' : '\\"',
		"\\": '\\\\'
		},
		encodeString : function(s){
		if (/["\\\x00-\x1f]/.test(s)) {
		return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
		var c = m[b];
		if(c){
		return c;
		}
		c = b.charCodeAt();
		return "\\u00" +
		Math.floor(c / 16).toString(16) +
		(c % 16).toString(16);
		}) + '"';
		}
		return '"' + s + '"';
		},
		encodeArray : function(o){
		var a = ["["], b, i, l = o.length, v;
		for (i = 0; i < l; i += 1) {
		v = o[i];
		switch (typeof v) {
		case "undefined":
		case "function":
		case "unknown":
		break;
		default:
		if (b) {
		a.push(',');
		}
		a.push(v === null ? "null" : this.encode(v));
		b = true;
		}
		}
		a.push("]");
		return a.join("");
		},
		encodeDate : function(o){
		return '"' + o.getFullYear() + "-" +
		pad(o.getMonth() + 1) + "-" +
		pad(o.getDate()) + "T" +
		pad(o.getHours()) + ":" +
		pad(o.getMinutes()) + ":" +
		pad(o.getSeconds()) + '"';
		},
		encode : function(o){
		if(typeof o == "undefined" || o === null){
		return "null";
		}else if(o instanceof Array){
		return this.encodeArray(o);
		}else if(o instanceof Date){
		return this.encodeDate(o);
		}else if(typeof o == "string"){
		return this.encodeString(o);
		}else if(typeof o == "number"){
		return isFinite(o) ? String(o) : "null";
		}else if(typeof o == "boolean"){
		return String(o);
		}else {
		var self = this;
		var a = ["{"], b, i, v;
		for (i in o) {
		if(!this.useHasOwn || o.hasOwnProperty(i)) {
		v = o[i];
		switch (typeof v) {
		case "undefined":
		case "function":
		case "unknown":
		break;
		default:
		if(b){
		a.push(',');
		}
		a.push(self.encode(i), ":",
		v === null ? "null" : self.encode(v));
		b = true;
		}
		}
		}
		a.push("}");
		return a.join("");
		}
		},
		decode : function(json){
		return eval("(" + json + ')');
		}
		};
