/**
 * @author rocky2000
 */

$(document).ready(function(){
	
	$(".form_script").each(function() 
	{
		addFormDiv($(this));
		showForm(getID($(this).attr("src")));
	});
	
});


function addFormDiv(form)
{
	var src = $(form).attr("src");
	var form_id = getID(src);
	
	$(form).after('<div id="website_form_'+form_id+'" style="width: 100%; position: relative;"></div>');
}

function showForm(website_form_id)
{
	
	var destination_url 		= 	"/form/get-form/";
	$.post(destination_url, {website_form_id: website_form_id}, function(result)
	{
		var data = result.html;
		$("#website_form_"+website_form_id).html(data);
		
		applyEvents();
	}, "json");
	return false;
}

function applyEvents()
{
	$(".form_form").ajaxSubmit();
}

function getID(querystring){ 

    //Create regular expression object to retrieve the qs part 
    var qsReg = new RegExp("[?][^#]*","i"); 
    hRef = unescape(querystring); 
    var qsMatch = hRef.match(qsReg); 

    //removes the question mark from the url 
    qsMatch = new String(qsMatch); 
    qsMatch = qsMatch.substr(1, qsMatch.length -1); 

    //split it up 
    var rootArr = qsMatch.split("&"); 

    for(i=0;i<rootArr.length;i++){ 
        var tempArr = rootArr[i].split("="); 
        if(tempArr.length ==2){ 
            return unescape(tempArr[1]); 
        } 
    } 
} 


$.fn.ajaxSubmit = function(e) 
{ 
	/* Change a form's submission type to ajax */ 
	this.submit(function()
	{ 
		var params = {}; 
		
		$(this) 
			.find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea") 
			.each(function() { 
				params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
			}); 
	
		var destination_url = "/form/submit-form/";
		$.post(destination_url, params, function(result)
		{
			var error = result.error;
			var data = result.html;
			
			if(error != "") alert(error);
			else $("#website_form_"+params['website_form_id']).html(data);
	
			return false;
			
		}, "json");
		
		return false;

	});
}