/**
 * $("a.myLink").ajaxlink( { contentBlockId: sContentBlockId, callBack: fCallBack } )
 *      convierte un enlace "normal" en un enlace que carga el contenido enlazado
 *      dentro un bloque en la p?ina actual. Si definido, llama a fCallBack
 *      al terminar pasandole como parametro el elemento insertado
 * $("form.myForm").ajaxform(  { contentBlockId: sContentBlockId, callBack: fCallBack }  )
 *      parecido al enlace, carga el resultado del formulario dentro de un bloque
 *      de la p?ina actual. Si definido, llama a fCallBack
 *      al terminar pasandole como parametro el elemento insertado
 *  TODO:
 *  poner en comun el codigo con popuplink, este es copipegado de aquel
 **/

$(document).ready( myOnLoad );
var sCalcDate = '<fmt:formatDate value="${hoy}" pattern="yyyy/MM/dd" />';

function myOnLoad(){
		setWindowSize();
    if( $("#content").height()< ($.session("wdwHeight")*.71) ) $("#content").height($.session("wdwHeight")*.71);
    if( $("#content").width()< ($.session("wdwWidth")*.93) ) $("#content").width($.session("wdwWidth")*.93);
    
    // enlaces "popup":
    	$("a.popup").popuplink();
    
  	// enlaces "AJAX":
  	$("a.ajaxLink").ajaxlink( { contentBlockId: "resultado", callBack: myOnLoad } );
  	$("form.ajaxForm").ajaxform( { contentBlockId: "content", callBack: myOnLoad } );
    
    try{ $('input.dateInput').css({width:"8em"}).datePicker(); } catch(e) {}  
    try{ $(function() { $('#navtabs').tabs({remote:true}); }); } catch(e) {}
    try{ onLoadDiv(); } catch(e) {}; 
    
    $('input[@type=text]').focus(function(){ 
      if($(this).val() == $(this).attr('defaultValue')) { 
         $(this).val('');
      } });
      $('input[@type=text]').blur(function(){
         if($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));
         } 
      });    
}

jQuery.fn.ajaxlink = function( options ){  
    return this.each(function(  ) {
        var settings = {
          contentBlockId : "resultado", // ID of the content to be extracted from the result page
          callBack : null
        };
        if( options ){ jQuery.extend( settings, options ); } 
        $( this ).click( function(){
            var sTargetSelector = $( this ).attr( "target" );
            var linkParams={rand:Math.random()};
            
            try{ jQuery.extend( linkParams, parametros ); } catch(e) {};
            
            $.get( $(this).attr("href"), linkParams, function( data ){
              var sContent = jQuery.ajaxlink.extractContent( data, settings.contentBlockId );
              if(sContent==null) sContent=data;;
              $( sTargetSelector ).hide().html( sContent ).show("slow");                        
              if( options.callBack != undefined ){ options.callBack( $( sTargetSelector ) ); }
            } );
            return false; // return false, so original link will  not be used!!
        } );
    });    
}
jQuery.fn.ajaxform = function( options ){  
    return this.each(function(  ) {
        var settings = {
          contentBlockId : "content", // ID of the content to be extracted from the result page
          callBack : null
        };
        if( options ){ jQuery.extend( settings, options ); }        
        $( this ).submit( function(){
            var sTargetSelector = $( this ).attr( "target" );
            $(this).ajaxSubmit( function( data ){
                var sContent = jQuery.ajaxlink.extractContent( data, settings.contentBlockId );
                //$( sTargetSelector ).hide().html( sContent ).show("slow");
								//alert("Mirar jquery.ajax.link.js --> "+sTargetSelector+this.id);
								$( sTargetSelector ).hide().html( data ).show("slow");
                if( options.callBack != undefined ){ options.callBack( $( sTargetSelector ) ); }
            });
            return false; // return false, so original form submit will  not be used!!
        } );
    });
}


jQuery.ajaxlink = {
    
    /* return the HTML of the "content" part of an HTML page */
    extractContent : function ( sHtmlPage, contentBlockId ){    
        // change the content ID so it will not match any possible content ID within the current page
        var sNewContentId = "cococontent";
        var contentRE = 'id="'+contentBlockId+'"'; // TODO: catch id="kaka" but also id='kaka' !!!!
        
        sHtmlPage = sHtmlPage.replace(contentRE, 'id="'+sNewContentId+'"');

        // create a hidden div and add the received HTML:
        var tempHiddenDiv = $("#tempHiddenDiv");
        if( tempHiddenDiv.length == 0 ){
            $( document.body ).append("<div id='tempHiddenDiv' style='display:none'></div>");
            tempHiddenDiv = $("#tempHiddenDiv");
        }
        tempHiddenDiv.html( sHtmlPage )

        return tempHiddenDiv.find( "#"+sNewContentId ).html();
    }
}
