$(function(){

				// Accordion
				$("#accordion").accordion({ header: "h3" });
	
				// Tabs
				$('#tabs').tabs();
	

				// Dialog			
				$('#dialog').dialog({
					autoOpen: false,
					width: 600,
					buttons: {
						"Ok": function() { 
							$(this).dialog("close"); 
						}, 
						"Cancel": function() { 
							$(this).dialog("close"); 
						} 
					}
				});
				
				// Dialog Link
				$('#dialog_link').click(function(){
					$('#dialog').dialog('open');
					return false;
				});

				// Datepicker
				$('#datepicker').datepicker({
					inline: true
				});
				
				// Slider
				$('#slider').slider({
					range: true,
					values: [17, 67]
				});
				
				// Progressbar
				$("#progressbar").progressbar({
					value: 20 
				});
				
				//hover states on the static widgets
				$('#dialog_link, ul#icons li').hover(
					function() { $(this).addClass('ui-state-hover'); }, 
					function() { $(this).removeClass('ui-state-hover'); }
				);
				
			});
			
			
			
	
/* Helper functions */
function checkLength(o,n,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("Length of " + n + " must be between "+min+" and "+max+".");
		return false;
	} else {
		return true;
	}

}
function updateTips(t) {
	tips
		.text(t)
		.addClass('ui-state-highlight');
	setTimeout(function() {
		tips.removeClass('ui-state-highlight', 1500);
	}, 500);
}

	


$(document).ready(function(){

	$(".opendialog").click(function() { // when clicking on a button
		adminDialog = setDialogType($(this).attr('id'),$(this).attr('title'),$(this).attr('rel'));
		adminDialog.dialog('open');
	});
});

/* Admin popups */
function setDialogType(dialogType, dialogTitle, dataSource) {
	var lang = $("html").attr("lang");
	dataSource = '/' + lang + dataSource;
	if (dialogType == 'adminModeTitle') {
		adminDialog = $("#dialog-adminModeTitle");
		adminDialog.dialog('destroy');
		setDialogTypeTitle(adminDialog, dataSource);
		
	} else if (dialogType == 'adminModeStatus') {
		adminDialog = $("#dialog-adminModeStatus");
		adminDialog.dialog('destroy');
		setDialogTypeStatus(adminDialog, dataSource);
	} else if (dialogType == 'adminModeLanguage') {
		adminDialog = $("#dialog-adminModeLanguage");
		adminDialog.dialog('destroy');
		setDialogTypeLanguage(adminDialog, dataSource);
	} else if (dialogType == 'adminModeURLpart') {
		adminDialog = $("#dialog-adminModeURLpart");
		adminDialog.dialog('destroy');
		setDialogTypeURLpart(adminDialog, dataSource);
	} else if (dialogType == 'adminModeParentID') {
		adminDialog = $("#dialog-adminModeParentID");
		adminDialog.dialog('destroy');
		setDialogTypeParentID(adminDialog, dataSource);
	} else if (dialogType == 'adminModeAddLink') {
		adminDialog = $("#dialog-adminModeAddLink");
		adminDialog.dialog('destroy');
		setDialogTypeAddLink(adminDialog, dataSource);
	} else if (dialogType == 'adminModeCreateNew') {
		adminDialog = $("#dialog-adminModeCreateNew");
		adminDialog.dialog('destroy');
		setDialogTypeCreateNew(adminDialog, dataSource);
	}
	
	adminDialog.dialog('option', 'title', dialogTitle);
	
	return adminDialog;
}

function setDialogTitleData(responseText) {
	$("#dialog-adminModeTitle").contents().find(":input").val(responseText);
}
function setDialogTypeTitle(adminDialog, dataSource) {
	var title = $("#title"),
			allFields = $([]).add(title),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 730,
		buttons: {
			'Save': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(title,"title",1,255);
				
				if (bValid) {
					// Push to server
					$.post(dataSource, { updateFragment: true, 'Title': title.val() }, reloadPage);
					$(this).dialog('close');
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			$(this).find(":input").val($.ajax({ url : dataSource, async: false }).responseText);
		}
	});
}

/* Dialog status */
function setDialogStatusData(responseText) {
	$("#dialog-adminModeStatus").contents().find(":input").val(responseText);
}
function setDialogTypeStatus(adminDialog, dataSource) {
	var status = $("#status"),
			allFields = $([]).add(status),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 730,
		buttons: {
			'Save': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				// Push to server
				$.post(dataSource, { updateFragment: true, 'Status': status.val() }, reloadPage);
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			$(this).find(":input").val($.ajax({ url : dataSource, async: false }).responseText);
		}
	});
}

/* Dialog language */
function setDialogLanguageData(responseText) {
	$("#dialog-adminModeLanguage").contents().find(":input").val(responseText);
}
function setDialogTypeLanguage(adminDialog, dataSource) {
	var language = $("#language"),
			allFields = $([]).add(language),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 730,
		buttons: {
			'Save': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				// Push to server
				$.post(dataSource, { updateFragment: true, 'Language': language.val() }, reloadPageWithNewLanguage);
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			$(this).find("#language").val($.ajax({ url : dataSource, async: false }).responseText);
		}
	});
}

/* Dialog URLpart */
function setDialogURLpartData(responseText) {
	$("#dialog-adminModeURLpart").contents().find(":input").val(responseText);
}
function setDialogTypeURLpart(adminDialog, dataSource) {
	var URLpart = $("#URLpart"),
			allFields = $([]).add(URLpart),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 730,
		buttons: {
			'Save': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				// Push to server
				$.post(dataSource, { updateFragment: true, 'URLpart': URLpart.val() }, reloadPageWithNewLanguage);
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			$(this).find("#URLpart").val($.ajax({ url : dataSource, async: false }).responseText);
		}
	});
}

/* Dialog ParentID */
function setDialogParentIDData(responseText) {
	$("#dialog-adminModeParentID").contents().find(":input").val(responseText);
}
function setDialogTypeParentID(adminDialog, dataSource) {
	var newParentID = $("#newParentID"),
			allFields = $([]).add(newParentID),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 1000,
		buttons: {
			'Save': function() {
				allFields.removeClass('ui-state-error');
				
				//console.log(" SAVING ",finalParentID);
				$.post(dataSource, { updateFragment: true, 'ParentID': finalParentID }, reloadPageWithNewLanguage);
				$(this).dialog('close');
			},
			Cancel: function() {
				$(':input[name=newParentID]').remove();
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			var lang = $("html").attr("lang");
			$.getJSON( '/'+lang+'/sitemap.json', function(json) {
				var currentSel = $.ajax({ url : dataSource, async: false }).responseText;
				var dataSource2 = window.location+'?fragment=PageID';
				var currentPageID = $.ajax({ url : dataSource2, async: false }).responseText;
				//console.log(" current Page ID : ",currentPageID);
				//console.log(" current Parent ID : ",currentSel);
				//var options = {preselect: {'Bienvenue': 1}}; // value for default option (include field name)

				var optionTree = $('input[name=newParentID]').optionTree(json,currentSel,currentPageID);
				
				finalParentID = currentSel;
			});
		}
	});
}

/* Dialog AddLink */
function setDialogAddLinkData(responseText) {
	$("#dialog-adminModeAddLink").contents().find(":input").val(responseText);
}
function setDialogTypeAddLink(adminDialog, dataSource) {
	var addLink = $("#addLink"),
			allFields = $([]).add(addLink),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 1000,
		buttons: {
			'Save': function() {
				allFields.removeClass('ui-state-error');
				
				//$.post(dataSource, { updateFragment: true, 'ParentID': finalParentID }, reloadPageWithNewLanguage);
				// use finalAddLink as ID for new link
				//alert(finalParentID);
				$('.AdminPageEdit_textarea').insertAtCaret('<ideaLink dest="@'+finalParentID+'"></ideaLink>');
				$(this).dialog('close');
			},
			Cancel: function() {
				$(':input[name=addLink]').remove();
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			var lang = $("html").attr("lang");
			$.getJSON( '/'+lang+'/sitemap.json', function(json) {
				var currentSel = $.ajax({ url : dataSource, async: false }).responseText;
				var dataSource2 = window.location+'?fragment=PageID';
				var currentPageID = $.ajax({ url : dataSource2, async: false }).responseText;

				var optionTree = $('input[name=addLink]').optionTree(json,currentSel,currentPageID);
			});
		}
	});
}

/* Dialog CreateNew */
function setDialogCreateNewData(responseText) {
	$("#dialog-adminModeCreateNew").contents().find(":input").val(responseText);
}
function setDialogTypeCreateNew(adminDialog, dataSource) {
	var newParentID = $("#newParentID"),
			allFields = $([]).add(newParentID),
			tips = $(".validateTips");

	adminDialog.dialog({
		autoOpen: false,
		modal: true,
		width: 1000,
		buttons: {
			'Save': function() {
				allFields.removeClass('ui-state-error');
				
				var lang = $("html").attr("lang");
				$.post(dataSource, { createNew: true, 'ParentID': finalParentID, 'lang': lang }, reloadPageWithNewLanguage);
				$(this).dialog('close');
			},
			Cancel: function() {
				$(':input[name=newParentID]').remove();
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		},
		open: function() {
			var lang = $("html").attr("lang");
			$.getJSON( '/'+lang+'/sitemap.json', function(json) {
				var currentSel = 0;
				var currentPageID = 0;
				var optionTree = $('input[name=newParentID]').optionTree(json,currentSel,currentPageID);
				
				finalParentID = currentSel;
			});
		}
	});
}

function reloadPage(response) {
	window.location.reload();
}
function reloadPageWithNewLanguage(response) {
	window.location = response;
}

function setDialogTypeExample() {
	$("#dialog").dialog({
		autoOpen: false,
		modal: true,
		buttons: {
			'Save': function() {
				var bValid = true;
				//allFields.removeClass('ui-state-error');

				/*bValid = bValid && checkLength(name,"username",3,16);
				bValid = bValid && checkLength(email,"email",6,80);
				bValid = bValid && checkLength(password,"password",5,16);

				bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
				// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
				bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([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])))\.?$/i,"eg. ui@jquery.com");
				bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
				
				if (bValid) {
					$('#users tbody').append('<tr>' +
						'<td>' + name.val() + '</td>' + 
						'<td>' + email.val() + '</td>' + 
						'<td>' + password.val() + '</td>' +
						'</tr>'); 
					$(this).dialog('close');
				}*/
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	});
}

$.fn.insertAtCaret = function (myValue) {
	return this.each(function(){
			//IE support
			if (document.selection) {
					this.focus();
					sel = document.selection.createRange();
					sel.text = myValue;
					this.focus();
			}
			//MOZILLA / NETSCAPE support
			else if (this.selectionStart || this.selectionStart == '0') {
					var startPos = this.selectionStart;
					var endPos = this.selectionEnd;
					var scrollTop = this.scrollTop;
					this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
					this.focus();
					this.selectionStart = startPos + myValue.length;
					this.selectionEnd = startPos + myValue.length;
					this.scrollTop = scrollTop;
			} else {
					this.value += myValue;
					this.focus();
			}
	});
};



$.extend({ getUrlVars: function(){    
	var vars = [], hash;    
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
	},  getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});
