/*
 * jQuery WG FORM AJAXIFY
 * Copyright (c) 2009 Roberto Lee (webgenerator.nl)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Date: 2010-11-02
 * Rev: 3
 */
/*
REQUIREMENTS

The post page must contain result wrapped around the div defined in the call.
*/
var regex_scriptstring = new RegExp("script","gi"); //Find all script tags
var regex_scriptdisabledstring = new RegExp("scriptdisabled","gi"); //Find all scriptdisabled tags
var regex_datachecker = new RegExp("(?:\.js|\<\/head\>)","gi"); // check for .js string and the closing head tag.
var nameofform = "form_ajaxified";
var regex_formsdots = new RegExp("•","gi");

$.ajaxSetup({
   	global: true,
	async: false,
	cache: false
});

(function($){
     $.fn.extend({
         WG_Forms_Ajaxify: function(options) { //Select the form to submit and process
	        var defaults = {
	        	source_url: '',
	        	source_container_form: '', //The new form object, usefull if form allready exists
	        	on_post_elem_messages_result: 'div#frm_messages',
	        	on_post_elem_messages_success: 'div#frm_success',
	        	relative_files: 'file.aspx,link.aspx,captcha.aspx',
	        	selector_fields_defaulted : '',
	        	defaultvalue_attribute: 'rel',
	        	message_on_ajax_error:'', //Show this error message, instead of xhr errormessage
				cb: function(){}
	        };
	        var options = $.extend(defaults, options);

            return $(this).each(function(idx) {
            	var html_elem = $(this);

            	//RETRIEVE FORM
				if($(html_elem).is('*'))
				{
							$.ajax({
								type: "GET",
								url: options.source_url,
								beforeSend: function(){
								},
								success: function(data){
									//$(html_elem).append("<form id=\""+nameofform+"\"/>");
									$(html_elem).html("<form id=\""+nameofform+"\"/>");

									var fullpath_formsmodule_arr = options.source_url.split("/");
									var fullpath_formsmodule = options.source_url.replace(fullpath_formsmodule_arr[fullpath_formsmodule_arr.length-1],'');

									jQuery.each(options.relative_files.split(','), function(i,val){
										var re = new RegExp(val, "g");
										//data = data.replace('file.aspx',fullpath_formsmodule+'file.aspx');
										data = data.replace(re,fullpath_formsmodule+val);
									});
									var ajax_result = $('<div/>').append($.trim(data.replace(regex_scriptstring,"scriptdisabled"))); //Rename the script tags, to disable it
									var ajax_result_form = ajax_result.find(options.source_container_form).is('*') ? ajax_result.find(options.source_container_form).html() : "";

									//$(ajax_result_form).find("img").attr('src','bbb');

									if(ajax_result_form != "") { $(html_elem).find("form#" + nameofform).append(ajax_result_form) } //Original form

									//alert($(html_elem).find("form#" + nameofform).html());
									$(html_elem).find("form#" + nameofform).WG_Forms_Ajaxify_Process({
										htmlelement: html_elem,
										process_url: options.source_url,
							        	on_post_elem_messages_result: options.on_post_elem_messages_result,
							        	on_post_elem_messages_success: options.on_post_elem_messages_success,
							        	selector_fields_defaulted: options.selector_fields_defaulted,
							        	defaultvalue_attribute: options.defaultvalue_attribute
									});
								},
								error: function(xhr, thrownError){
									var errMsg =  $.trim(options.message_on_ajax_error) != "" ? options.message_on_ajax_error : xhr.statusText + " ("+xhr.status+")";
									$(html_elem).html(errMsg);
								},
								complete: function(){
									options.cb.call();
								}
						});
				}


            });
		}
    });
})(jQuery);




(function($){
     $.fn.extend({
         WG_Forms_Ajaxify_Process: function(options) {
	        var defaults = {
	        	htmlelement: '',
	        	process_url: '',
	        	on_post_elem_messages_result: '',
	        	on_post_elem_messages_success: '',
	        	selector_fields_defaulted: '',
	        	defaultvalue_attribute: ''
	        };
	        var options = $.extend(defaults, options);
            return $(this).each(function(idx) {
            	var formajax = $(this);
				formajax.submit(function() {
									if(options.selector_fields_defaulted != '')
									{
										$(options.selector_fields_defaulted).each(function (i) {
											//EMTPTY IF DEFAULT VALUE IS SUBMITTED
											$(this).data("vals", {
												defaultvalue: $.trim($(this).attr(options.defaultvalue_attribute)),
												userinputvalue: $.trim($(this).val())
											});
											if($(this).data("vals").defaultvalue == $(this).data("vals").userinputvalue)
											{
												$(this).val('');
											}
										});
										var serializedata = formajax.serialize();
										$(options.selector_fields_defaulted).each(function (i) {
											//RESTORE
											if($(this).val()== '')
											{
												$(this).val($(this).data("vals").defaultvalue);
											}
										});
									}
									else
									{
										var serializedata = formajax.serialize();
									}

									//PROCESS FORM
									$.ajax({
											type: "POST",
											url: options.process_url,//.replace("ion","x"),
											data: serializedata,
											beforeSend: function(){
											},
											success: function(data){
													var new_ajaxpost_result = "";
													var ajaxpost_result = $('<div/>').append($.trim(data.replace(regex_scriptstring,"scriptdisabled")));

													if(ajaxpost_result.find(options.on_post_elem_messages_result).is('*')) //are there messages?
													{
														new_ajaxpost_result = ajaxpost_result.find(options.on_post_elem_messages_result).html();
														{
															if($(options.elem_form_messages).is('*'))
																$(options.elem_form_messages).html(new_ajaxpost_result);
															else
																//alert(" " + $.trim(($(new_ajaxpost_result).text().replace(re_formsdots, "\n"+"-"))));
																alert($(new_ajaxpost_result).text().replace(regex_formsdots, "\n"+"-"));
														}
													}
													if(ajaxpost_result.find(options.on_post_elem_messages_success).is('*')) //did the form resulted in a success?
													{
														new_ajaxpost_result = ajaxpost_result.find(options.on_post_elem_messages_success).html();
														new_ajaxpost_result = $('<div/>').append($.trim(new_ajaxpost_result.replace(regex_scriptdisabledstring,"script")));
														$(options.htmlelement).html(new_ajaxpost_result);
													}
											},
											error: function(xhr, thrownError){
												var errMsg =  $.trim(options.message_on_ajax_error) != "" ? options.message_on_ajax_error : xhr.statusText + " ("+xhr.status+")";
												alert(errMsg);
											},
											complete: function(){
												return false;//Disable the normal submit
											}
									});
									return false; //Disable the normal submit
				});

            });
		}
    });
})(jQuery);
/*
 * jQuery WG Forms Default Value
 * Copyright (c) 2009 Roberto Lee (webgenerator.nl)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Date: 2009-09-02
 * Rev: 1
 * UNUSED IN THIS PLUGIN
 */
(function($){
     $.fn.extend({
         WG_Forms_DefaultValue: function(options) { //Select the form to submit and process

			var defaults = {
	        	default_value_color: '#ACACAC',
	        	filled_value_color: '#000000',
	        	defaultvalue_attribute: 'rel',
				cb: function(){}
	        };

	        var options = $.extend(defaults, options);

            return $(this).each(function(idx) {
            	var inputfield = $(this);
				var defaultvalue = inputfield.attr(options.defaultvalue_attribute);

				inputfield.bind("focus click blur",function(){
					inputfield.css('color', options.filled_value_color);
					if (inputfield.val() == defaultvalue)
					{
						inputfield.val("");
					}
				});

				inputfield.blur(function(){
					SetDefaultValue();
				});

				function SetDefaultValue()
				{
					if ((inputfield.val() == "") || (inputfield.val() == defaultvalue))
					{
						inputfield.val(defaultvalue).css('color', options.default_value_color);
					}
				}
				SetDefaultValue();

            	options.cb.call();
            });

		}
    });
})(jQuery);



(function($) {

   $.fn.log = function(msg) {
      if (typeof (console) == "undefined") {
         console = { log: function() { } };
      }
      if (console) {
         console.log("%s: %o", msg, this);
      }
      return this;
   }
})(jQuery);

jQuery.log = function(msg) {
      if (typeof (console) == "undefined") {
         console = { log: function() { } };
      }
      if (console) {
         console.log("%s: %o", msg, this);
      }
};

/*EXAMPLE USAGE
<script src="http://www.mcmconnexion.nl/jquery.js" type="text/javascript"></script>
<script src="http://www.mcmconnexion.nl/jquery.wg_forms_ajaxify.js" type="text/javascript"></script>
<SCRIPT type=text/javascript>
//<![CDATA[
try {
	   jQuery(document).ready(function() {
	          jQuery("div.my_form").WG_Forms_Ajaxify({
	                          source_url: 'http://www.interim-eventmanager.nl/forms_lite/default.aspx?fid=6',
	                          source_container_form: 'form[name="form6"]',
	                          base_url_app: 'http://www.interim-eventmanager.nl/forms_lite/',
	                          selector_fields_defaulted: '#my_form input[type=text], #my_form textarea',
	                          cb: function(){
									var inpvaluefields = "#my_form input[type=text], #my_form textarea";
									$(inpvaluefields).each(function(){
									    $(this).attr('rel',$(this).parent("td").prev("td").text().replace(':',''));
									    $(this).parent("td").prev("td").hide();
									});
									$("#form_ajaxified input[type=text], #form_ajaxified textarea").WG_Forms_DefaultValue();
	                          }
	          });
	   });
} catch(e){};
//]]>
</SCRIPT>

//Add this line in "Javascript (primair bedoeld voor codes zoals bijv. Google Adwords conversiecode)" field
<div id="frm_success"><br />Uw aanvraag is verstuurd: u hoort snel van ons!<br /></div>

//Replace message code in template form.wgt
	<$MESSAGES
		globalprefix="<TR><TD colspan=3><div id='frm_messages'><FONT color=red>"
		prefix="&#149; "
		postfix="<BR>"
		globalpostfix="</FONT></div></TD></TR>"
	$>
*/
