// Global lookup arrays for base64 conversions
var enc64List, dec64List;
// Load the lookup arrays once
function initBase64() {
    enc64List = new Array();
    dec64List = new Array();
    var i;
    for (i = 0; i < 26; i++) {
        enc64List[enc64List.length] = String.fromCharCode(65 + i);
    }
    for (i = 0; i < 26; i++) {
        enc64List[enc64List.length] = String.fromCharCode(97 + i);
    }
    for (i = 0; i < 10; i++) {
        enc64List[enc64List.length] = String.fromCharCode(48 + i);
    }
    enc64List[enc64List.length] = "+";
    enc64List[enc64List.length] = "/";
    for (i = 0; i < 128; i++) {
        dec64List[dec64List.length] = -1;
    }
    for (i = 0; i < 64; i++) {
        dec64List[enc64List[i].charCodeAt(0)] = i;
    }
}

function base64Encode(str) {
    var c, d, e, end = 0;
    var u, v, w, x;
    var ptr = -1;
    var input = str.split("");
    var output = "";
    while(end == 0) {
        c = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end = 1) ? 0 : 0);
        d = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end += 1) ? 0 : 0);
        e = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end += 1) ? 0 : 0);
        u = enc64List[c >> 2];
        v = enc64List[(0x00000003 & c) << 4 | d >> 4];
        w = enc64List[(0x0000000F & d) << 2 | e >> 6];
        x = enc64List[e & 0x0000003F];
        
        // handle padding to even out unevenly divisible string lengths
        if (end >= 1) {x = "=";}
        if (end == 2) {w = "=";}
        
        if (end < 3) {output += u + v + w + x;}
    }
    // format for 76-character line lengths per RFC
    var formattedOutput = "";
    var lineLength = 76;
    while (output.length > lineLength) {
    	formattedOutput += output.substring(0, lineLength) + "\n";
    	output = output.substring(lineLength);
    }
    formattedOutput += output;
    return formattedOutput;
}

function base64Decode(str) {
    var c=0, d=0, e=0, f=0, i=0, n=0;
    var input = str.split("");
    var output = "";
    var ptr = 0;
    do {
        f = input[ptr++].charCodeAt(0);
        i = dec64List[f];
        if ( f >= 0 && f < 128 && i != -1 ) {
            if ( n % 4 == 0 ) {
                c = i << 2;
            } else if ( n % 4 == 1 ) {
                c = c | ( i >> 4 );
                d = ( i & 0x0000000F ) << 4;
            } else if ( n % 4 == 2 ) {
                d = d | ( i >> 2 );
                e = ( i & 0x00000003 ) << 6;
            } else {
                e = e | i;
            }
            n++;
            if ( n % 4 == 0 ) {
                output += String.fromCharCode(c) + 
                          String.fromCharCode(d) + 
                          String.fromCharCode(e);
            }
        }
    }
    while (typeof input[ptr] != "undefined");
    output += (n % 4 == 3) ? String.fromCharCode(c) + String.fromCharCode(d) : 
              ((n % 4 == 2) ? String.fromCharCode(c) : "");
    return output;
}

// Self-initialize the global variables
initBase64();

// jFrame
// $Revision: 1.80 $
// Author: Frederic de Zorzi
// Contact: fredz@_nospam_pimentech.net
// Revision: $Revision: 1.80 $
// Date: $Date: 2007/11/08 15:17:18 $
// Copyright: 2007 PimenTech SARL
// Tags: ajax javascript pimentech english jquery



jQuery.fn.waitingJFrame = function () {
	// Overload this function in your code to place a waiting event 
	$(this).html("<div class='loading'></div>");
}


jQuery.fn.getJFrameTarget = function () {
    // Returns first parent jframe element, if exists
    var div = jQuery(this).parents("div[@src]").get(0);
    if (div) {
        var target = jQuery(this).attr("target");
        if (target) {
            return jQuery("#" + target);
        }
    }
    return jQuery(div);
};


jQuery.fn.loadJFrame = function(url, callback) {
    // like ajax.load, for jFrame. the onload attribute is supported
    var this_callback = jQuery(this).attr("onload");
    callback = callback || function(){ };
    url = url || jQuery(this).attr("src");
    if (url && url != "#") {
			contenido.push($('#contenido').html());
			jQuery(this).waitingJFrame();
			jQuery(this).load(url, 
									 function() { 
											 jQuery(this).attr("src", url);
											 jQuery(this).activateJFrame(); 
											 jQuery(this).find("div[@src]").each(function(i) {
															 jQuery(this).loadJFrame();
													 } );
											 eval(this_callback);
											 callback();
									 });
    }
    else {
			jQuery(this).activateJFrame(); 
    }
};

jQuery.fn.activateJFrame = function() {
  // Add an onclick event on all <a> and <input type="submit"> tags
	jQuery(this).find("a")
	.not("[jframe='no']")
    .unbind("click")
    .click(function() { 
            var target = jQuery(this).getJFrameTarget();
            if (target.length) {
                var href = jQuery(this).attr("href");
                if (href && href.indexOf('javascript:') != 0) {
									//Preparar link para el historial
									var hash = href;
									//Asegurar que el link luego de # en caso de tenerlo
									hash = hash.replace(/^.*#/, '');
									//cambio link
									hash = (hash && hash.indexOf('?') == -1) ? hash + "?incluido=1" : hash + "&incluido=1";
									//Cargar marco
                  target.loadJFrame(hash);
									//Asegurar link historico
									hash = base64Encode(hash);
									//Agregar entrada de historial
									$.history.load(hash);
									return false;
                }
            }
            return true;
        } );

		jQuery(this).find('[id^="submit_"]')
		.not("[jframe='no']")
    .unbind("click")
    .click(function() {
			var input = this;
			var target = jQuery(input).getJFrameTarget();
			if (target.length) {
				var form = input.form;
				form = form || $('#' + $(this).attr('form'));
				if (form.onsubmit && form.onsubmit()==false) {
					return false;
				}
				target.waitingJFrame();
				jQuery(form).ajaxSubmit({ 
					target: target,
					beforeSubmit: function(formArray) { 
						formArray.push({ 
							name:"submit", 
							value: jQuery(input).attr("value") 
						}); 
					},
					success: function() { 
						target.attr("src", jQuery(form).attr("action"));
						eval(target.attr("onload"));
						target.activateJFrame(); 
					}
				});
				return false;
			}
			return true;
		} );
	
	jQuery(this).find("form")
    .unbind("submit")
    .submit(function() {
			return false;
		} );
};


jQuery(document).ready(function() { 
	jQuery(document).find("div[@src]").each(function(i) {
			jQuery(this).loadJFrame();
			if (jQuery(this).attr("src") && jQuery(this).attr("src") != "#") {
			}
	} );
} );
