/**
 *
 * Core.js
 *
 */

//
// Perform callback to a window[section] function
//
function callback(f, m, data) {
	if (!f || !m) return;
	if (!data) data = {};
	if (typeof(window[f["section"]])=='object') {
		if (typeof(window[f["section"]][f["method"][m]])=='function') {
			if (window[f["section"]][f["method"][m]](data)) {
				return true;
			}
		}
	}
}

//
// Create object from all input elements in any given section
//
function objectFromInputs(ip, m, p) {
	var r = {};
	
	try {
		(ip instanceof $) || (ip = $(ip));
		
		// Check all text input fields
		ip.find(":input").each(function() {
			var $this = $(this);
			var type = $this.attr('type');
			var add = true;
			// Special case input fields that must be "checked"
			switch (type) {
				case "radio":
					if ($this.attr('checked')==false) add = false;
					break;
				case "checkbox":
					if ($this.attr('checked')==false) add = false;
					break;
			}
			if (add) {
				r[$(this).attr("name")] = $(this).val();
			}
		});
	} catch(e) {} // Don't care
	
	(m) && (r.message = m);
	(p) && (r.partial = p);
	
	return r;
}

//
// Create object from the attributes of any given object
//
function objectFromAttributes(node) {
	var data = {}, 
		node = $(node)[0];
	
	// Wrap body with jQuery.  This will do nothing if the node is already 
	// jQuery, will find it if it is a selector, and wrap it if it is an  
	// HTMLElement
	node = $(node);
	
	// See if body is form 
	if(node.attr("nodeName") == "FORM") {
		// Let jQuery erialize the form  
		data = node.serialize();
	} else if(node.attr("nodeName")) { // Is this an HTMLElement?  
		// Extract attributes from the element...
		$(node.attr("attributes")).each(function() {
			// Does this attribute have a name?
			(this.nodeName)
			// Does this attribute (not) already exist in data?
			&& (data[this.nodeName])
			// Set the attribute in the data
			|| (data[this.nodeName] = this.nodeValue);
		});
	}
	
	return data;
	
	// I changed the function header, it used to be as follows [sjd]
	// function objectFromAttributes(ip, p) {

// I commented this out because I couldn't read or understand it and there 
// were no comments.  I also made it much smaller and I hope I retained
// the old functionality [sjd]
//	var data 	= {};
//	(ip instanceof $) || (ip = $(ip));
//	if (typeof(p)!='object') p = {};
//	ip.each(function() {
//		for (key in this.attributes) {
//			if (typeof(this.attributes[key])=='object') {
//				var name 	= this.attributes[key].nodeName;
//				var value 	= this.attributes[key].nodeValue;
//				var add		= true;
//				if (typeof(p.ignore)=='string') p.ignore = [p.ignore];
//				if (typeof(p.ignore)=='object') {
//					for (k in p.ignore) {
//						var attr = p.ignore[k];
//						if (attr.toString()==name.toString()) add = false;
//					}
//				}
//				if (add) data[name] = value;
//			}
//		}
//	});
//	return data;
}

function printArray(item) {
	var p, m = [];
	
	for(p in item) m.push(p + ' = ' + item[p]);
	m.sort();
	alert(m.join("\n"));
}

// http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getScroll() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return { x: scrOfX, y: scrOfY };
}

/**
 * Creates an error box
 * 
 * @param	data			object containing the following parameters
 * @param	data.title		Title of the confirmation box
 * @param 	data.html		Contents of the confirmation box
 * @param	data.onClose	Function to perform on confirm
 * 
 * @return
 */
function error(data) {
	if (typeof(data)!='object') return;
	var div = $("<div \/>").appendTo("body");
	if (!data["html"]) data.html = "There was an error!";
	if (!data["title"]) data.html = "Error";
	if (!data["data"]) data.data = {};
	div.html(data["html"]).dialog({
		modal	: true,
		title	: data["title"],
		buttons	: {
			Ok		: function() {
				div.dialog("close");
			}
		},
		close	: function() {
			if (typeof(data["onClose"])=='function') {
				data.onConfirm(data.data);
			}
			div.remove();
		}
		}).dialog("open");
}

//
// Test the browser
//
function checkBrowser() {
	var ie = ($.browser.msie && parseInt($.browser.version)<=6) ? true : false ;
	if(ie) {
		error({
			title	: "Crappy Browser Alert!",
			html	: "Hey punk! We have detected that you are using a crappy browser (Internet Explorer 6.0). Get a real browser like Firefox or Safari!"
		});
	}
};

/**
 * deleteCookie
 * 
 * @param name
 * @param path
 * @param domain
 */
function deleteCookie( name, path, domain ) {
	document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
};

/**
 * setCookie
 * 
 * @param c_name
 * @param value
 * @param expiredays
 */
function setCookie(c_name, value, expiredays) {
	deleteCookie(c_name);
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
};

/**
 * valid
 * 
 * Run basic form validation
 * 
 * @param $form	jQuery object containing the form
 */
function valid($form) {
	var data = objectFromInputs($form);
	$form.find(".required").each(function(){
		if ($(this).val()=="" || $(this).hasClass("error")) {
			$(this).addClass("error");
			data = false;
		}
	});
	return data;
};

// 
// Serialize enhancements
//
(function($) {
	var f = ["old", "serialize", new Date().getTime()].join("-");
	
	$.fn[f] = $.fn.serialize;
	
	$.fn.serialize = function() {
		var data = {}, 
		
		// Wrap body with jQuery.  This will do nothing if the node is already 
		// jQuery, will find it if it is a selector, and wrap it if it is an  
		// HTMLElement
		node = $(this);
		
		// See if body is form 
		if(node.attr("nodeName") == "FORM") {
			// Let jQuery serialize the form  
			data = node[f]();
		} else if(node.attr("nodeName")) { // Is this an HTMLElement?  
			// Extract attributes from the element...
			$(node.attr("attributes")).each(function() {
				// Does this attribute have a name?
				(this.nodeName)
				// Does this attribute (not) already exist in data?
				&& (data[this.nodeName])
				// Set the attribute in the data
				|| (data[this.nodeName] = this.nodeValue);
			});
		}
		
		return data;
	};
})(jQuery);
