

Dialog = function() {};

Dialog.ERROR = -1;
Dialog.WARNING = 1;
Dialog.NOTICE = 2;
Dialog.INFO = 4;

Dialog.show = function (message, type, timeout, modal) {
	$('#dialog').find('.message').html(message);
	$('#dialog').dialog({modal: true, draggable: false});
	$('#dialog').dialog('open');
	
	$('#dialog').find('.buttons button.ok').bind('click', function (){$('#dialog').dialog('close');} );
};

/**
 * Auto attachments
 */
$(document).ready(function(){
	$("form").each(Six.initForm);
});

Six = function() {};

// Error dialog handling
Six.ajax = {
	isError : function( r ) {
		if( r.status == -1 ) {
			Dialog.show(r.message, Dialog.ERROR);
			return true;
		} else {
			return false;
		}
	}
};

// Six validators
Six.form = function() {};

Six.form.toggleErrorMessage = function( el, msg, on ) {
	$(el).next(".validate-error").remove();
	if (on) {
		$(el).after('<div class="validate-error">' + msg + '</div>');
	}
};

// All available form validators
Six.form.validators = {
	required : function( el ) {
		var result = false;
		if(el.val() != null) {
			if($.isArray(el.val())) {
				result = (el.val().length > 0);
			} else {
				result = (jQuery.trim(el.val()) != "");				
			}
		}
		el.toggleClass("validate-error", !result);
		return result;
	},
	
	email : function( el ) {
		if (jQuery.trim( el.val() ) == '') {
			return true;
		}

		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var result = filter.test( el.val() );
		Six.form.toggleErrorMessage( el, "You must provide a valid email address", !result );
		el.toggleClass("validate-error", !result);
		return result;
	},
	
	phone : function ( el ) {
		var result = true;
		if (jQuery.trim( el.val() ) == '') {
			return result;
		}

		var filter = /^[0-9]{10,11}$/;
		var phone = el.val().replace(/[^0-9]/g, '');
		result = filter.test( phone );
		
		phone = phone.substring(phone.length - 10, phone.length);
		if(el.val().length > 9) {
			el.val("(" + phone.substring(0,3) + ") " + phone.substring(3, 6) + "-" + phone.substring(6,10));
		}
		Six.form.toggleErrorMessage( el, "You must provide a valid phone number", !result );
		el.toggleClass("validate-error", !result);
		return result;
	},
	
	match : function ( el ) {
		var matchers = [];
		var frm = $(el).parents('form:first');
		var elems = $(frm).find('[validator]');
		for (var i = 0; i < elems.length; i++) {
			var vld = $(elems[i]).attr("validator").split(";");
			for(var v in vld) {
				if (vld[v] == 'match') {
					matchers.push(elems[i]);
				}
			}
		
		}
		
		var valid = true;
		for (var m = 1; m < matchers.length; m++) {
			if (matchers[m].value != matchers[m-1].value) {
				valid = false;
				
			}
		}
		for (var m = 0; m < matchers.length; m++) {
			Six.form.toggleErrorMessage( matchers[m], 'All confirm fields must match their partner.', !valid);
		}
		return valid;
	}
	
};

// Validates an entire form
Six.form.validate = function( frm, cb ) {

	var valid = true;
	if ($(frm).attr('validate') != "true") {
		return valid;
	}
	
	$(frm).find("*[validator]").each(function() {
		valid = Six.form.validateField( $(this) ) ? valid : false;
	});
	
	if ($(frm).attr('requireCategory') == 'true') {
		var categoryInputs = $(frm).find('[name="category_id[]"]');
		var hasCategory = false;
		for (var i = 0; i < categoryInputs.length; i++) {
			if (categoryInputs[i].checked) {
				hasCategory = true;
			}
		}
		
		if (!hasCategory) {
			$('#topicSelector').jqmShow();
		    $('#topicSelector .error').html('<strong>You must choose at least one category to post this content to.</strong>');
		    valid = false;
		}
	}
	
	if (Six.form.fckEditor) {
		var text = Six.util.trim(Six.form.fckEditor.GetHTML());
		//Couldn't figure out where the startup value was config'd and it starts with a BR
		if (text == '' || text == '<br>' || text == '<br />') {
			$('#fckError').html('<strong>Body must have text</strong>');
			valid = false;
		}
	}
	return valid;
	
};

// Validates a form element
Six.form.validateField = function( el ) {
	var valid = true;
	var vld = el.attr("validator").split(";");
	for(var v in vld) {
		eval("valid = Six.form.validators." + vld[v] + "( el );");
	}
	return valid;
};

Six.form.fckEditor = null;

// Prepares the Ajax call
Six.initForm = function() {
	var frm = $(this);
	if(frm.attr("validate") == 'true') {
			frm.find('[validator]').each(function() {
				var vld = $(this).attr("validator").split(";");
				var required = false;
				for(var v in vld) {
					if (vld[v] == 'required') {
						required = true;
					}
				}
				
				if (required) {
					var id = $(this).attr("id");
					var label = $(frm).find('[for="' + id + '"]');
					label.html(label.html() + " <span class=\"required\">*</span>");
				}
				
				$(this).bind("blur", function(e) {
					Six.form.validateField( $(this) );
				});
			});
		
		frm.find('input[redirect], button[redirect]').bind("click", function(e) {
			e.preventDefault();
			window.location.href = $(this).attr("redirect");
		});
	
		$(this).bind("submit", function(e) {
			if( $(this).attr("formType") == "ajax" ) {
				e.preventDefault();
				if ( Six.form.validate($(this)) ) {
					var callback =  ($(this).attr('callback')) ? eval($(this).attr('callback')) : Six.defaultCallback;
					$.post($(this).attr('action'), $(this).serialize(), callback, "json");
				}
			} else {
				if (!Six.form.validate($(this))) {
					e.preventDefault();
				}
			}
		});
	}
};


// If <form>.callback is not specified this will be called
Six.defaultCallback = function(r) {
	if (Six.ajax.isError(r)) {
		return;
	} else {
		Dialog.show(r.message, Dialog.NOTICE);
	}
};


// Organization callbacks
Six.org = {

	create : function(r) {
		if (Six.ajax.isError(r)) {
			return;
		}
		
		Six.util.redirect('/org/registration-complete');

	}

};



Six.cookie = function () {};


Six.cookie.create = function (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=/";
};

Six.cookie.read = function () {
	        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;
};

Six.util = function(){};

Six.util.trim = function (str){
	return str.replace(/^\s+|\s+$/g, '');
}

Six.util.reload = function() {
	window.location.href = window.location.href;
}

Six.util.redirect = function(href) {
	window.location.href = href;
}


