

Dialog = function() {};

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

Dialog.show = function (message, type, timeout, modal, title) {
	$('#dialog').find('.message').html(message);
	
	$('#dialog').dialog({
		modal: true, 
		draggable: false,
		resizable: false
	});
	
	$('#dialog').dialog('open');
	
	
	// if there's a jqm already up, we want the dialog above it.
	$('#dialog')
		.parents().filter('.ui-dialog')
		.css('z-index', 5003);
	$('.ui-widget-overlay')
		.css('z-index', 5002);
	
	
	$('#dialog').find('.buttons button.ok').bind('click', function (){$('#dialog').dialog('close');} );
};

/**
 * Auto attachments
 */
$(document).ready(function(){
	$("form").each(Six.initForm);
	$("[enablerFor]").bind('change', Six.toggleEnable)
});

Six = function() {};

//Essentially lets a checkbox enabled/disable another element
Six.toggleEnable = function(e) {
	var check = $(this);
	var targetId = check.attr('enablerFor');
	var target = $('#'+targetId);
	target.attr('disabled', !target.attr('disabled'))
};


// 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;
	},
	
	ccdate : function( el ) {
		var result = true;
		if (jQuery.trim( el.val() ) == '') {
			return result;
		}

		var result = el.val().match(/^\d{2}\/\d{4}$/);
		
		Six.form.toggleErrorMessage( el, "Date is in incorrect format", !result );
		el.toggleClass("validate-error", !result);
		return result;
	}
	
};

// 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) {
		// Added && valid at the end, otherwise the last validator wins the battle.
		// This makes it so all validators must eval to true to return true, not just the last one.
		eval("valid = (Six.form.validators." + vld[v] + "( el ) && valid);");
	}
	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>");
				}
				
				if ( $(this).attr('validateOn') != 'submitOnly') {
					$(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");
		});
		
		frm.find('input[back], button[back]').bind("click", function(e) {
			e.preventDefault();
			history.go(-1);
		});
		
		$(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');

	},
	
	addRow : function() {
		var num = parseInt($('#userTable .num:last').html());
		num += 1;
		
		var row = $('#userTable tr:last');
		var newRow = row.clone(true);
		
     	// clear inputs
		$(newRow).find(':input').val('');
    	
    	$(newRow).find('td:last').html('<a href="" onclick="Six.org.removeRow(this); return false">Remove Row</a>');
    	$(newRow).find('td:first').html(num);
    	$('#userTable').append(newRow);
    	$(newRow).find('input:first').focus();
	},
	
	removeRow : function(elem) {
		var row = $(elem).parents('tr').remove();
		this.resequence();
	},
	
	resequence : function() {
		var nums = $('#userTable .num');
		for (var i = 0; i < nums.length; i++)  {
			$(nums[i]).html(i+1);
		}
	},
	
	checkPromoCallback : function(r) {
		alert(r.message);
		if (r.data.skipBilling) {
			Six.util.redirect('/org/confirm');
		}
	}
};



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;
};

Six.util.toggleShowReplies = function(link) {
	link = $(link);
	var id = link.attr('childrenId');
	var elem = $('#children'+id);
	
	if (elem.is(":hidden")) {
		elem.slideDown("fast");
		link.html('Hide Replies');
	} else {
		elem.slideUp("fast");
		link.html('Show Replies');
	}
};

//2009-03-20
(function($){

$.fn.extend({

	/**
	 * Stores the original version of offset(), so that we don't lose it
	 */
	_offset : $.fn.offset,
	
	/**
	 * Set or get the specific left and top position of the matched
	 * elements, relative the the browser window by calling setXY
	 * @param {Object} newOffset
	 */
	offset : function(newOffset){
	    return !newOffset ? this._offset() : this.each(function(){
			var el = this;
			
			var hide = false;
			
			if($(el).css('display')=='none'){
				hide = true;
				$(el).show();
			};
			
			var style_pos = $(el).css('position');
			
			// default to relative
			if (style_pos == 'static') {
				$(el).css('position','relative');
				style_pos = 'relative';
			};
			
			var offset = $(el).offset();
			
			if (offset){
				var delta = {
					left : parseInt($(el).css('left'), 10),
					top: parseInt($(el).css('top'), 10)
				};
				
				// in case of 'auto'
				if (isNaN(delta.left)) 
					delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
				if (isNaN(delta.top))
					delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;
				
				if (newOffset.left || newOffset.left===0)
					$(el).css('left',newOffset.left - offset.left + delta.left + 'px');
			
				if (newOffset.top || newOffset.top===0)
					$(el).css('top',newOffset.top - offset.top + delta.top + 'px');
			};
			if(hide) $(el).hide();
		});
	}

});

})(jQuery);