/**
 * set up namespaces
 */
vwd4 = (typeof(vwd4) === 'undefined') ? {} : vwd4;
vwd4.cms_forms = (typeof(vwd4.cms_forms) === 'undefined') ? {} : vwd4.cms_forms;

jQuery(document).ready(function () {
  vwd4.cms_forms.load();
});


vwd4.cms_forms.load = function() {
  //show wicket/server errors
  $('.ajax_form_container').ajaxError(function(info,xhr){
    $(info.target).append(xhr.responseText);
  });

  var url = $('.ajax_form_container a').attr('href');
  if(url){
    vwd4.cms_forms.ajaxWicketLoad(url);
  }
};

vwd4.cms_forms.ajaxWicketLoad = function(pUrl) {
  $.get(pUrl, function(pData) {
    vwd4.cms_forms.appendAjaxResponse(pData);
  });
};

vwd4.cms_forms.appendAjaxResponse = function(pData) {
  var formWrapper = $("<div />").append(pData.replace(/<script(.|\s)*?\/script>/g, "")).find('#wicket_form_content_wrapper');

  var container = $('.ajax_form_container');
  container.empty();
  container.append(formWrapper);
  vwd4.cms_forms.bindAjaxSubmit();
  var scripts = pData.match(/<script(.|\s)*?\/script>/g);
  var srcRegexp = /<script.+src="(.[^"\?]*)(\?.[^\"])?".*>.*/;
  if(scripts) {
    for (i=0; i<scripts.length; i++) {
      var func = function(index) {
        return function() {
          // append script block to head
          var script = scripts[index];
          $('head').append(script);
          
          // append additional dummy script block with src_ attribute to make sure wicket does not load its js twice (see DINT-250)
          // strip of any URL parameters that may be appended to the url (for whatever reasons)
          var srcs = srcRegexp.exec(script);
          if (srcs && srcs.length>1) {
            // add dummy script element via DOM code and not jQuery to avoid having it removed by jQuery instantly
            var scriptElement = document.createElement('script');
            scriptElement.setAttribute('src_', srcs[1]);
            document.getElementsByTagName('head')[0].appendChild(scriptElement);
          }
          
          if (typeof(Wicket) != 'undefined' && Wicket.Event && Wicket.Event.addDomReadyEvent) {
            Wicket.Event.addDomReadyEvent = function(fn) {
              fn();
            };
          }
        };
      }(i);
      // try to fix ie6-problem with inserting script-tags
      if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        setTimeout(func, 50+1000*i);
      }
      else {
        func();
      }
    }
  }
  vwd4.cms_forms.frontendPE(container);
};


vwd4.cms_forms.bindAjaxSubmit = function() {
  $('.ajax_form_container form').unbind('submit');
  $('.ajax_form_container form button[class!="ajaxsubmit"][type!="button"]').unbind('click').click(vwd4.cms_forms.ajaxSubmit);

};


vwd4.cms_forms.ajaxSubmit = function(event) {
  // prevent default
  event.preventDefault();

  // get element from event
  var targetElement = $(event.target);

  // do submit
  vwd4.cms_forms.doAjaxSubmit(targetElement);

  // cancel default event
  return false;
};


vwd4.cms_forms.doAjaxSubmit = function (pTargetElement) {
  var form = $('.ajax_form_container form');
  // DSE-218/DSE-190: At least in Webkit the target element is not necessarily the button element itself,
  // but an element nested within that was clicked upon (span/canvas etc.).
  // In that case we fetch the closest button ancestor element for retrieving its name
  var submitButton = pTargetElement.is('button') ? pTargetElement : pTargetElement.closest('button');

  var formFields = form.serializeArray();

  var buttonObject = { name: submitButton.attr('name'), value: ''};
  formFields.push(buttonObject);
  // DVDI-538: Supply the sling encoding parameter to make the servlet engine transcode the parameters properly
  formFields.push({ name: "_charset_", value: "UTF-8" });

  //get url
  var url = form.attr('action');
  // post
  $.post(url, formFields, function(pData) {
    vwd4.cms_forms.appendAjaxResponse(pData);
  });

};


//call to frontend method to apply its progressive enhancement
vwd4.cms_forms.frontendPE = function(pContainer) {
  if (vwd4 && vwd4.utils && vwd4.utils.refreshAjaxContent) {
    vwd4.utils.refreshAjaxContent(pContainer);
  }
};
