
/*

-----------------------
jquery.Mosoni.AJAX.js
Created: 10/16/08
Last Modified: 10/31/08
-----------------------

*/

function loadToggleDiv(url, location, callObject, showText, hideText) {
	if(!showText) showText = CLOUD_SHOW_TEXT;
	if(!hideText) hideText = CLOUD_HIDE_TEXT;
	if($(callObject).attr("loaded")) {
		toggleDiv(location, callObject, showText, hideText);
	}
	else {
		var text = $(callObject).html();
		
		setObjectText(callObject, CLOUD_LOADING_TEXT, true);
		
		$.get(url, function(data) {
			$("#"+location).html(data);
			$("#"+location).slideDown();
			$(callObject).attr({loaded: true});
			$(callObject).html(text.replace(showText, hideText));
			setObjectText(callObject, text.replace(showText, hideText), false);
		});
	}
}

function loadForm(url, callObject, options) {
	
	var text = "";
	if(callObject) {
		text = $(callObject).html();
		setObjectText(callObject, CLOUD_LOADING_TEXT, true);
	}	else showActivity(CLOUD_LOADING_TEXT);

	$("#formOverlayContainer .form").html('<div class="loading_graphic"><img src="/images/loader.gif" /></div>');
	$("#formOverlayContainer").show();
	
	$.get(url, function(data){
		$("#formOverlayContainer .form").html(data);
		$("#formOverlayContainer").tinyscrollbar();
		if(callObject) setObjectText(callObject, text, false);
		else showActivity();
		if(options && options.callback) options.callback.call();
	})
}

function loadContent(url, location, callObject, callback) {
	var text = "";
	if(callObject) {
		text = $(callObject).html();
		setObjectText(callObject, CLOUD_LOADING_TEXT, true);
	} else if(typeof location == "string") {
		showActivity(CLOUD_LOADING_TEXT);
		$("#"+location).block({message: null});
	} else {
		showActivity(CLOUD_LOADING_TEXT);
		
		var parentContainer = location['parentContainer'];
		var locations = location['childContainers'];
		var blockLocation = location['blockContainer'];
		
		found = true;
		
		for(var i = 0; i < locations.length; i++) {
			if($("#"+locations[i]).length == 0) {
				found = false;
				break;
			}
		}
		
		if(!found) {
			location = parentContainer;
			$("#"+location).html('<div class="loading_graphic" style="height: '+$("#"+location).height()+'px;"><img src="/images/loader.gif" /></div>');
		} else {
			$("#"+blockLocation).html('<div class="loading_graphic" style="height: '+$("#"+location).height()+'px;"><img src="/images/loader.gif" /></div>');
		}
	}
	
	$.get(url, function(data){
		if(typeof location == "string") {
			$("#"+location).unblock();
			if($(data).attr("id") == location) $("#"+location).replaceWith(data); 
			else $("#"+location).html(data);
		}
		else {
			for(var i = 0; i < locations.length; i++) {
				$("#"+locations[i]).html($(data).find("#"+locations[i]).html());
			}
		}
		
		if(callObject) setObjectText(callObject, text, false);
		else showActivity();
		if(callback) setTimeout(callback, 0);
	})
}

function loadPostContent(url, form, location, options) {
//	$("#"+location).block();

	$.post(url, $("#"+form).serialize(), function(data) {
		$("#"+location).html(data);
		
//		$("#"+location).unblock();

		if(options && options.callback) setTimeout(options.callback, 0);
	});
}

function submitForm(url, form, options, processingText, failureText, successText) {
	if(!processingText) processingText = CLOUD_SAVING_TEXT;
	if(!failureText) failureText = CLOUD_ERROR_TEXT;
	if(!successText) successText = CLOUD_SAVED_TEXT;
	
	if($("#"+form).find(".submitButton").length != 0) {
		button = $("#"+form).find(".submitButton");
		while($(button).children().length > 0) button = $(button).children()[0];
		
		var oldHtml = $(button).html();
		
		setButtonText("#"+form, ".submitButton", processingText, true);
	} else showActivity(processingText);
	
	if(options && options.replaceDiv) $("#"+options.replaceDiv).block({message: null});
		
	if(options && options.progressMessage) {
		$("#progressOverlay .message").html(options.progressMessage);
		$("#progressOverlay").show();
	}
	
	$.post(url, $("#"+form).serialize(), function(data) {
		if(options && options.htmlData) {
			if(options.replaceEntry && $("#"+options.list).find("#"+options.replaceEntry).length != 0) {
				$("#"+options.replaceEntry).replaceWith(data);
			}
			else if(options.replaceDiv && $("#"+options.replaceDiv).length != 0) {
				$("#"+options.replaceDiv).html("");
				$("#"+options.replaceDiv).replaceWith(data);//fadeOut(function() {$("#"+options.replaceDiv).html(data); $("#"+options.replaceDiv).fadeIn()});
			}
			else if(options.keepForm){
				$("#"+options.list).prepend(data);
			} else if(options.targetId) {
				$("#"+options.targetId).html(data);
			} else {
				$("#"+form).parent().html("");
				if($("#"+options.list+" > .saveOrder").length != 0) $("#"+options.list+" > .saveOrder").before(data);
				else if(options.prepend) $("#"+options.list).prepend(data);
				else $("#"+options.list).append(data);
			}
			
			setButtonText("#"+form, ".submitButton", successText, true);
		}
		else {
			$("#"+form+" label.error").remove();
			if($(data).find("error").length > 0) {
				setButtonText("#"+form, ".submitButton", failureText, true);
				
				$(data).find("error").each(function() {
					var name = $(this).find("name").text();
					var value = $(this).find("value").text();
					$("#"+name).after("<label for=\""+name+"\" class=\"error\">"+value+"</label>");
				})
				
				var failed = true;
			} else if($(data).find("message").length > 0) {
				setButtonText("#"+form, ".submitButton", $(data).find("message").text(), true);
				
			} else if($(data).find("replace").length > 0) {
				$(data).find("replace").each(function() {
					var location = $(this).find("location").text();
					var content = $(this).find("content").text();
					$("#"+location).fadeOut(function() {$("#"+location).html(content); $("#"+location).fadeIn()});
				})
				
			} else {
				setButtonText("#"+form, ".submitButton", successText, true);
			}
		}
		
		if($(data).find("redirect").length > 0) {
			window.location = $(data).find("redirect").text();
		} else if($(data).find("redirect-hash").length > 0) {
			$.history.load($(data).find("redirect-hash").text());
		} else setTimeout("setButtonText('#"+form+"', '.submitButton', '"+oldHtml+"', false)", 1000);

		if(!failed && $("#formOverlayContainer").is(":visible") && (!options || !options.keepOverlay)) $("#formOverlayContainer").hide();
		else if($("#formOverlayContainer").is(":visible")) $("#formOverlayContainer").tinyscrollbar_update('relative');
		if(options && options.progressMessage) {
			$("#progressOverlay").hide();
			$("#progressOverlay .message").html("");
		}
		if(!failed && options && options.callback) setTimeout(options.callback, 0);
	});
}


function submitData(url, data, callObject, options, processingText, failureText, successText, confirmed) {
	if(processingText === undefined) processingText = CLOUD_SAVING_TEXT;
	if(failureText === undefined) failureText = CLOUD_ERROR_TEXT;
	if(successText === undefined) successText = CLOUD_SAVED_TEXT;
	
	var oldHtml = $(callObject).html();
	
	setObjectText(callObject, processingText, true);
	
	if(options && options.confirm && confirmed === undefined) {
		$("#deleteConfirmDiv .message").html(options.message);
		$("#deleteConfirmDiv .yes").click(function() {submitData(url, data, callObject, options, processingText, failureText, successText, true);});
		$("#deleteConfirmDiv .no").click(function() {submitData(url, data, callObject, options, processingText, failureText, successText, false);});
		$("#deleteConfirmDiv").show();
	} else if(options && options.confirm && !confirmed) {
		setObjectText(callObject);
		$("#deleteConfirmDiv").hide();
		$("#deleteConfirmDiv .yes").unbind("click");
		$("#deleteConfirmDiv .no").unbind("click");
	} else {
		$.post(url, data, function(data) {
			if(options && options.htmlData) {
				
				if(options.replaceEntry && $("#"+options.list).find("#"+options.replaceEntry).length != 0) {
					$("#"+options.replaceEntry).replaceWith(data);
				}
				else if(options.replaceDiv && $("#"+options.replaceDiv).length != 0) {
					$("#"+options.replaceDiv).replaceWith(data);//fadeOut(function() {$("#"+options.replaceDiv).html(data); $("#"+options.replaceDiv).fadeIn()});
				}
				else if(options.keepForm){
					$("#"+form)[0].reset();
					$("#"+options.list).prepend(data);
				} else if(options.targetId) {
					$("#"+options.targetId).html(data);
				} else {
					if($("#"+options.list+" > .saveOrder").length != 0) $("#"+options.list+" > .saveOrder").before(data);
					else $("#"+options.list).append(data);
				}
				
				setObjectText(callObject, successText, true);
				setTimeout(function() {setObjectText(callObject, oldHtml, false);}, 1000);
				if(options.list) setDataRowOddEvenClass(options.list);
			} else {
				if($(data).find("error").length > 0) {
					setObjectText(callObject, failureText, true);
					
					$(data).find("error").each(function() {
						var name = $(this).find("name").text();
						var value = $(this).find("value").text();
						$("#"+name).after("<label for=\""+name+"\" class=\"error\">"+value+"</label>");
					})
				} else if($(data).find("message").length > 0) {
					setObjectText(callObject, $(data).find("message").text(), true);
					
				} else if($(data).find("replace").length > 0) {
					$(data).find("replace").each(function() {
						var location = $(this).find("location").text();
						var content = $(this).find("content").text();
						$("#"+location).fadeOut(function() {$("#"+location).html(content); $("#"+location).fadeIn()});
					});
				} else {
					setObjectText(callObject, successText, true);
				}
		
				if($(data).find("redirect").length > 0 && window.location.pathname+window.location.search+window.location.hash != $(data).find("redirect").text()) {
					window.location.href = $(data).find("redirect").text();
				} else if($(data).find("redirect-hash").length > 0) {
					$.history.load($(data).find("redirect-hash").text());
				} else setTimeout(function() {setObjectText(callObject, oldHtml, false);}, 1000);
			}
	
			if(options && options.confirm) {
				$("#deleteConfirmDiv").hide();
				$("#deleteConfirmDiv .yes").unbind("click");
				$("#deleteConfirmDiv .no").unbind("click");
			}	
			if($("#formOverlayContainer").is(":visible") && (!options || !options.keepOverlay)) $("#formOverlayContainer").hide();
			else if($("#formOverlayContainer").is(":visible")) $("#formOverlayContainer").tinyscrollbar_update('relative');
			if(options && options.callback) options.callback.call();
		});
	}
}

function deleteEntry(url, options, callObject, confirmed) {
	if(confirmed === undefined) {
		$("#deleteConfirmDiv .message").html(options.message);
		$("#deleteConfirmDiv .yes").click(function() {deleteEntry(url, options, callObject, true);});
		$("#deleteConfirmDiv .no").click(function() {deleteEntry(url, options, callObject, false);});
		$("#deleteConfirmDiv").show();
	} else if(confirmed) {
		var linkText = $(callObject).html();
		setObjectText(callObject, CLOUD_DELETING_TEXT, true);
		$.post(url, options.data, function(data){
			if($(data).find("error").length == 0) {
				$("#"+options.entryId).remove();
				showActivity();
				setDataRowOddEvenClass(options.listId, options.dataClass);
			} else {
				setObjectText(callObject, $(data).find("error value"), true);
				setTimeout(function() {$(callObject).remove();showActivity()}, 2000);
			}
			$("#deleteConfirmDiv").hide();
			$("#deleteConfirmDiv .yes").unbind("click");
			$("#deleteConfirmDiv .no").unbind("click");
		});
	} else {
		setObjectText(callObject);
		$("#deleteConfirmDiv").hide();
		$("#deleteConfirmDiv .yes").unbind("click");
		$("#deleteConfirmDiv .no").unbind("click");
	}
}

function setButtonText(containerId, buttonId, text, disable) {
	setObjectText($(containerId+" "+buttonId), text, disable);
}

function setObjectText(callObject, text, disable) {
	if(disable) showActivity(text);
	else showActivity();
	if($(callObject).is("button")) {
		if(disable) $(callObject).attr("disabled", true);
		else $(callObject).removeAttr("disabled");
	} else {
		if(disable) $(callObject).block({message: null});
		else $(callObject).unblock({message: null});
	}
	if($("#activity_container").length == 0) $(callObject).html(text);
}

function showActivity(text) {
	if(text) {
		$("#activity_container").html(text);
		if(!$("#activity_container").is(":visible")) $("#activity_container").slideDown("fast"); 
	} else {
		$("#activity_container").slideUp("fast", function() {$("#activity_container").html("");});
	}
}

function getJSONOptions(url, input, options) {
	$(input).removeOption(/./);
	$.getJSON(url, function(data) {
		if(options.emptyReplacement && data.length == 0) {
			$(input).hide();
			$(options.emptyReplacement).show();
		} else {
			if(options.emptyReplacement) {
				$(input).show();
				$(options.emptyReplacement).hide();
			}
			if(options.firstValue) {
				$(input).addOption(options.firstValue, options.firstName);
			}
			addJSONOption(input, options, data, "");
		}
		
		if(options.fireChange) {
			$(input).change();
		}
		
		if(options.callback) options.callback.call();
	});
}

function addJSONOption(input, options, data, name) {
	for(var i = 0; i < data.length; i++) {
		thisName = name == "" ? data[i][options.nameKey] : name+" > "+data[i][options.nameKey];
		$(input).addOption(data[i][options.valueKey], thisName, (options.selectedValue ? data[i][options.valueKey] == options.selectedValue : false));
		if(data[i]["children"] instanceof Array) addJSONOption(input, options, data[i]["children"], thisName);
	}
}
