// Overlay / postloading ajax views

// enable the debugging alerts.
var ajax_unique_id_count = 0;
var ajax_view_target = "";
var ajax_view_callback = null;    // callback function pointer

/**
   with this function you can load a ajax view
   and the result will be displayed
   @param  url         the url from the view which should be loaded
   @param  target_id   the dom-id from the target (usualy a div)
*/
function loadAjaxView(url, target_id, callback){

   ajax_view_target = target_id;
   if (callback){
	   ajax_view_callback = callback;
   }
   else{
       ajax_view_callback = null;
   }
   $.get(url, {}, onAjaxViewLoaded);
}


function onAjaxViewLoaded(data){
    var node = $("#"+ajax_view_target);
    node.empty().append(data).hide().show("slow");

    if ($.browser.msie){
        // lovely msie does not execute the scripts automatically
        // lets do it "by hand"
        node.evalScripts();
    }

    forms = $("form", node);
    for (var i=0; i<forms.length; i++){
        ajax_unique_id_count++;
        var unique_id = "ajaxform_"+ajax_unique_id_count;

        forms[i].setAttribute("id", unique_id);
        forms[i].setAttribute("name", unique_id);

        // now map a onsubmit function onto the form
        forms[i].onsubmit = function(){
           return submitAjaxForm(this);
        };
    }
    if (ajax_view_callback){
       ajax_view_callback.call();
    }

    // reload oewa-pixel, if new content is loaded
    try {
        recountOEWA()
    } 
    catch(err) {}
}


/**
    the form also needs to be submitted via ajax.
    we use the html settings from the html form to
    support get/post.
*/

function submitAjaxForm(f){
    var param_str = "";
    $(f)
        .find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea")
        .filter(":enabled")
        .each(function() {
/*            params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;*/
            param_str += '&' + (this.name || this.id || this.parentNode.name || this.parentNode.id) +"="+ this.value;
        });
    $.post($(f).attr("action"), param_str, onAjaxViewLoaded);
    return false;
}