(function($){
    $.fn.enquiry = function(options) {
        var defaults = {
        		title:'Email enquiry',
        		legend:'Your contact details',
				companyEmail:'enquiries@street-directory.com.au',
				companyName: window.location,
				id:0,
        		fields:[
	        		        {
	        		        	label:'Name',
	        		        	id:'name',
	        		        	type:'text',
	        		        	mandatory:true
	        		        },
	        		        {
	        		        	label:'Email',
	        		        	id:'email',
	    		        		type:'text',
	    		        		mandatory:true,
	    		        		comment:'a copy of enquiry will be sent if email is given'
	        		        },
	        		        {
	        		        	label:'Mobile',
	        		        	id:'mobile',
	        		        	type:'text'
	        		        },
	        		        {
	        		        	label:'Phone',
	        		        	id:'phone',
	        		        	type:'text'
	        		        },
	        		        {
	        		        	label:'Your enquiry',
	        		        	id:'enquiry',
	        		        	type:'textarea',
	        		        	mandatory:true
	        		        }
        		        ],
		        webService: 'http://www.street-directory.com.au/libraries/api/email_enquiry/ws/enquiry.php',
		        errorMessage:'Your enquiry cannot be processed',
		        successMessage:'Thank you for your enquiry. We will contact you shortly',
		        noticeContainer:'#eq_notice',
		        fieldColon:false,
		        submitLabel:'Submit'
        };
        var options = $.extend(defaults, options);
        
        return this.each(function() {
            obj = $(this);
            
            obj.html('<h2>' + options.title + '</h2>');
            obj.append('<div id="eq_notice"></div><!-- end #eq_notice --><form></form>');
            obj.find('form').append('<fieldset></fieldset>');
            obj.find('fieldset').append('<legend>' + options.legend + '</legend>');
			
			obj.find('form').append('<input type="hidden" name="eq_cmail" id="eq_cmail" value="' + options.companyEmail + '" />');
			obj.find('form').append('<input type="hidden" name="eq_cname" id="eq_cname" value="' + options.companyName + '" />');
			obj.find('form').append('<input type="hidden" name="eq_id" id="eq_id" value="' + options.id + '" />');
            
            var totalFields = options.fields.length;
            
            for (var i=0; i<totalFields; i++) {
            	var field = options.fields[i];
            	var entry = createEntry(field, options.fieldColon);
            	obj.find('fieldset').append(entry);
            }
            
            obj.find('fieldset').append('<input type="submit" id="eq_submit" name="eq_submit" value="' + options.submitLabel + '" class="submit" />');
            
            obj.find('input.submit').click(function() {
            	var errors = 0;
            	obj.find('.mandatory').each(function() {
            		if ($(this).val().length == 0) {
            			$(this).addClass('error_box');
            			errors += 1;
            		} else {
            			$(this).removeClass('error_box');
            		}
            	});
            	
            	if (errors > 0) {
            		$(options.noticeContainer).html('<p class="error">Cannot process form, please check highlight field(s)</p>');
            	} else {
            		var formSerialize = obj.find('form').serialize();
            		var url = options.webService + "?" + formSerialize;
            		$.getJSON(url + "&jsoncallback=?", function(data) {
            			var status = data.status;
        				$(options.noticeContainer).empty();
            			if (status == "error") {
            				$(options.noticeContainer).html('<p class="' + status + '">' + options.errorMessage + '</p>');
            			} else {
            				obj.html('<p class="' + status + '">' + options.successMessage + '</p>');
            			}
            		});
            	}
            	
            	return false;
            });
        });
    }
    
    function createEntry(f, colon) {
    	var label = f.label;
    	var type = f.type;
    	var id = createId(f.id);
    	
    	var mandatory = (f.mandatory == true) ? '<em>*</em>' : '';
    	
    	var entry = '<label for="' + id + '">' + label + mandatory + '</label>';
    	
    	if (colon == true) {
    		entry += '<span class="colon">:</span>';
    	}
    	
    	if (type == 'text') {
    		entry += createTextField(id, f);
    	} else if (type == 'textarea') {
    		entry += createTextArea(id, f);
    	} else if (type == 'select') {
    		entry += createSelect(id, f);
    	} else if (type == 'checkbox') {
    		entry += createCheckBox(id, f);
    	}
    	
    	entry += '<br />';
    	
    	if (f.comment) {
    		entry += '<span class="comment">' + f.comment + '</span><br />';
    	}
    	
    	return entry;
    }
    
    function createId(text) {
    	return 'eq_'+ text.toLowerCase().replace(/ /ig, "_");
    }
    
    function createTextField(id, f) {
    	var mandatory = (f.mandatory == true) ? 'class="mandatory"' :'';
    	return '<input type="text" name="' + id + '" id="' + id + '" ' + mandatory + ' />';
    }
    
    function createTextArea(id, f) {
    	var mandatory = (f.mandatory == true) ? 'class="mandatory"' :'';
    	return '<textarea id="' + id + '" name="' + id + '" ' + mandatory + '></textarea>';
    }
    
    function createSelect(id, f) {
    	var options = '<option value="">- Please select -</option>';
    	
    	var selected = (f.selected && f.selected > 0) ? f.selected : 0;
    	var values = f.values;
    	
    	var totalValues = values.length;
    	
    	if (totalValues > 0) {
    		for (var i=0; i<totalValues; i++) {
    			var value = values[i];
    			var sel = ((i+1) == parseInt(selected)) ? 'selected="selected"' : '';
    			
    			options += '<option value="' + value + '" ' + sel + '>' + value + '</option>';
    		}
    	}
    	
    	return '<select id="' + id + '" name="' + id + '">' + options + '</select>';
    }
    
    function createCheckBox(id, f) {
    	var entry = '';
    	var values = f.values;
    	var total = values.length;
    	
    	if (total>0) {
    		for (var i=0; i<total; i++) {
    			var value = values[i];
    			entry += '<input type="checkbox" id="' + id + '[]" name="' + id + '[]" value="' + value + '" class="checkbox" /> ' + value+ '<br />';
    		}
    	}
    	
    	return '<span class="checkboxes">' + entry + '</span>';
    }
})(jQuery);
