/*
 *
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: does not validate that the final text is a valid number
 * (that could be done by another script, or server-side)
 *
 * @name     numeric
 * @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(",");
 * @example  $(".numeric").numeric(null, callback);
 *
 */
jQuery.fn.numeric = function(decimal, callback)
{
	decimal = decimal || ".";
	callback = typeof callback == "function" ? callback : function(){};
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
				{
					allow = false;
				}
				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)
				{
					allow = true;
				}
			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function()
		{
			var val = jQuery(this).val();
			if(val != "")
			{
				var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
				if(!re.exec(val))
				{
					callback.apply(this);
				}
			}
		}
	)
	return this;
}

$(document).ready(function () 
{
	$(".numeric").numeric();
	$('fieldset.collapsible > legend').each(function() 
	{
		var fieldset = $(this.parentNode);
		var text = this.innerHTML;
		var x = $('<div class="fieldset-wrapper"><\/div>').append(fieldset.children(':not(legend)'));

		$(this).empty().append(
			$('<a href="#">'+ text +'<\/a>').click(function() 
			{
				var parents = $(this).parents('fieldset:first');
				var fieldset = parents[0];
				toggleFieldset(fieldset);
				return false;
			})).after(x);
	});
});

function toggleFieldset(fieldset) 
{
	if ($(fieldset).is('.collapsed')) 
	{
		var content = $('> div', fieldset).css('display', 'none');
		$(fieldset).removeClass('collapsed');
		content.slideDown(300, function() 
		{
			// Make sure we open to height auto
			$(this).css('height', 'auto');
		});
	} 
	else
	{
		var content = $('> div', fieldset).slideUp('medium', function()
		{
			$(this.parentNode).addClass('collapsed');
		});
	}
}

// used in block items_action
function switchFavorite(item_id, item, action, element)
{
	var data = {favorites: action, item_id: item_id, item: item};

	$.post(SBR_URL + 'ajaxed.php', data, function(resp) {
		resp = eval('(' + resp + ')');
		if (false == resp['err'])
		{
			$(element).html(resp['msg']);
			$(element).unbind('click');
			$(element).bind('click', function() {
				action = 1 == action ? -1 : 1; // switch action
				switchFavorite(item_id, item, action, this);
				return false;
			});
		}
	});
}

// handle mail sending to members
jQuery.fn.mail_form = function(options)
{
	// collect data and submit it
	var submit = function()
	{
		var data = {};
		$(attr['form'] + ' :input').each(function() {
			data[this.name] = this.value;
		});
		
		$.post(attr['url'], data, attr['succsess']);
	}

	// handle server response
	var succsess = function(data)
	{
		data = eval('(' + data + ')');
		var notif = $('<div />').addClass(data['err'] ? 'error' : 'notification');
		for (var i = 0; i < data.msg.length; i++)
		{
			notif.append(lang[data['msg'][i]] + '<br />');
		}
		$('#mf_notify').html(notif).jqmShow();
		setTimeout('$("#mf_notify").jqmHide()', 4000);
	}

	var attr = jQuery.extend({
		form: '#mail_form',
		url: SBR_URL + 'ajaxed.php',
		submit: submit,
		succsess: succsess
	}, options);

	var load_form = function()
	{
			// get HTML form
			$.get(SBR_URL+'js/mail_form.htm', function(data) {
				data = translate(data); // translate form
				$('body').append(data); // append form to document

				form = $(attr['form']);
				if (typeof attr['to'] != 'undefined')
				{
					$("input[name='recip']", form).val(attr['to']);
				}
				$('img', form).attr('src', SBR_URL+'image.php?h='+Math.random()); // set CAPTCHA
				$("input[lang='submit']", form).bind('click', attr['submit']);
				form.jqm({trigger: false}).jqmShow(); // bind jqModal plugin and show form
				$('#mf_notify').jqm();
			});
	}

	$(this).bind('click', function() {
		var form = $(attr['form']);
		if (!form.length)
		{
			load_form();
		}
		else
		{
			form.jqmShow();
		}
		return false;
	});
}

/**
 * translate document
 */
function translate(doc)
{
	// convert string into jQuery object
	doc = $('<div/>').append(doc);
	if ('object' == typeof(lang))
	{
		$('span[lang], label[lang]', doc).each(function() {
			var lang_key = $(this).attr('lang');
			$(this).html(lang[lang_key]);
		});
		$('input[lang]', doc).each(function() {
			var lang_key = $(this).attr('lang');
			$(this).val(lang[lang_key]);
		})
	}
	return $(doc).html();
}

function isEmail(email)
{
	return email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i);
}

/**
 * show selected plan fields
 * @param int aPlanId Plan ID
 */
var sbr = typeof sbr == 'undefined' ? {} : sbr;
sbr['lastPlan'] = 0;
function showPlanFields(aPlanId)
{
	$('.plan_' + sbr['lastPlan']).hide();
	$('.plan_' + aPlanId).show();
	sbr['lastPlan'] = aPlanId;
}

