function processKeyPress(e, f)
{
    if(!e || !f)
        return;

    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
    {
     	f();
    }
}

$.fn.ajaxSubmit = function(e) {
    /* Change a form's submission type to ajax */
    this.submit(function(){
	    var params = { form_id: this.getAttribute("id"), parent_id: $(this).parent().get(0).getAttribute("id") };

	    $(this)
	    .find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea")
	    .filter(":enabled")
	    .each(function() {
		    var key = this.name || this.id || this.parentNode.name || this.parentNode.id;
		    if(key.substr(key.length - 2) == '[]')
		    {
			if(this.value.replace(new RegExp('^[\\s]*$', "g"), "") != '')
			{
			    if(typeof(params[key]) == 'object' && (params[key] instanceof Array))
			    {
				params[ key ][ params[key].length ] = this.value;
			    }
			    else
			    {
				params[ key ] = [this.value];
			    }
			}
		    }
		    else
		    {
			params[ key ] = this.value;
		    }
		});

	    $("body").addClass("curWait");

	    $.post(this.getAttribute("action"), params);
	    return false;
	});
    return this;
}

$.ajaxSetup({
    error:function(x,e){
        debug = (x.responseText.match(/exception/) != null);

	if(x.status==0){
	    return;//message = 'You are offline!!\n Please Check Your Network.';
	}else if(x.status==404){
	    message = 'Requested URL not found.';
	}else if(x.status==500){
	    match = x.responseText.match(/\[ERROR\]:(.*):\[ERROR\]/);
	    if(match != null){
		message = match[1];
	    }
	    else{
		message = 'An error has occured.';
	    }
	}else if(e=='parsererror'){
	    message = "Error.\nParsing JSON Request failed.";
	}else if(e=='timeout'){
	    message = 'Request Time out.';
	}else {
	    message = 'Unknow Error.';
	}

	//show_message(message, { class: 'ui-state-error show-error' + ((debug)?' show-debug':''), no_fade: debug });
    }
});

function show_error(message, options)
{
    if(options == null)
	options = {};
    if(options['class'] == null)
	options['class'] = 'ui-state-error show-error';
    show_message(message, options)
}

function show_success(message, options)
{
    if(options == null)
	options = {};
    if(options['class'] == null)
	options['class'] = 'show-success';
    show_message(message, options)
}

function show_message(message, options)
{
    var message_id = 'msg_' + Math.floor(Math.random()*10000);

    $('#Header').after("<div class='" + ((options['class'])?' ' + options['class']:'') + "' id='" + message_id + "'>" +
		       message +
		       ((options['no_fade'])?"<div style='float:right;'><a href='javascript:$(\"#" + message_id + "\").slideUp(500);void(0);'>hide</a></div><div class='clear'></div>":'') +
		       "</div>");
    $('#' + message_id).slideDown(500);
    if(!options['no_fade'])
	setTimeout("$('#" + message_id + "').slideUp(500);",7000);    
}

$.fn.showSuccess = function(success_message) {
    return this.each(function() {
	    show_success(success_message);
	});
};

$.fn.showError = function(error_message) {
    return this.each(function() {
	    show_error(error_message);
	});
};

$.fn.alert = function(message) {
    return this.each(function() {
	    alert(message);
	});
};

function redirect(location) { window.location = location; }

$.fn.redirect = function(location) {
    return this.each(function() {
	    redirect(location);
	});
};

function refresh() { window.location.reload(); }

$.fn.refresh = function() {
    return this.each(function() {
	    refresh();
	});
};

function initLogin() {
    $('.input-username').fadeIn();
    $('.input-password').fadeIn();
    $('.form-login').each(function() { checkVip( $(this).attr('id'), $('#'+$(this).attr('id')+' .input-username').val()); });
}
function checkVip(form_id, username) {
    $.post('/ajax/login/check_vip/'+form_id+'/'+username);
}
function emptyCart() { 
    var confirmation = confirm("Empty all the contents of your shopping cart?");
    if(!confirmation){ return;}
    $.post('/ajax/products/empty_cart'); 
}

$.fn.emptyCart = function() {
    return this.each(function() {
	    emptyCart();
	});
};

function updateCart() { $.post('/ajax/products/update_cart_totals'); }
$.fn.updateCart = function() {
    return this.each(function() {
	    updateCart();
	});
}

function cartSwap(e) { 
    $.post('/ajax/products/swap/', { add: $(e).attr('checked'), data: $(e).val() });
    $("[value='"+$(e).val()+"']").attr('checked', $(e).attr('checked'));
}

function bulkCartSwap(container_id) {
    var cbs = '';
    var not_first = 0;
    $('#'+container_id+' input:checkbox').each( function() { 
	    if(not_first)
		cbs = cbs +',';
	    cbs = cbs+'"'+$(this).val()+'":"'+$(this).attr('checked')+'"'; 
	    not_first = 1;
	});
    $.post('/ajax/products/bulk_swap/', { data: '{'+cbs+'}' });
}
