/*
 *   _____                                 _             _                    
 *  / ____|                               | |           | |                   
 * | |      ___  _ __ ___  _ __   ___  ___| |_  __ _  __| | ___  _ __ ___ ___ 
 * | |     / _ \| '_ ` _ \| '_ \ / _ \/ __| __|/ _` |/ _` |/ _ \| '__/ _ | __|
 * | |____| (_) | | | | | | |_) | (_) \__ \ |_| (_| | (_| | (_) | | |  __|__ \
 *  \_____|\___/|_| |_| |_| .__/ \___/|___/\__|\__,_|\__,_|\___/|_|  \___|___/
 *                        | |                                                 
 *                        |_|
 *                        
 * [main.js] iquadrat 2010
 * 
 * 		Script principal
 *
 */


/*
 * Control de errores
 */
window.onerror = function(msg, url, linenumber) {
	return true;
};

/*
 * Init
 */
$(document).ready(function(){
	
	$(document).pngFix();
	
	// Menus desplegables
	$(".ul_li").mouseover(function(){
		$(this).css('z-index', 99);
		$('ul', this).show();
	}).mouseout(function(){
		$(this).css('z-index', 0);
		$('ul', this).hide();
	});
	
	// Rollover del glosario
	$('span.glosario').glosario({
		glosario_url: __("/glosario/")
	});
	
	// Click en contacto
	$("#contacto").bind("click", function(){
		document.location = "/" + __("contacto");
	});

	// Submit del buscador
	$("#fbuscador").bind("submit", function(){
		if($("#tbuscador").val() != "") {
			if($("#tbuscador").val().length >= 2) {
				//document.fbuscador.submit();
				return true;
			} else {
				message(__("Busqueda demasiado corta, el m�nimo son 2 caracteres."));
				return false;
			}
		} else {
			message(__("Tienes que introducir alguna busqueda."));
			return false;
		}
		
	});
	
	// Click para el boton del buscador
	$("#ibuscador").click(function(){
		$("#fbuscador").submit();
	});
	
	// Fancybox
	$("a.fancybox").fancybox({
		'overlayShow': true,
		'hideOnOverlayClick': true,
		'hideOnContentClick': false,
		'autoDimensions': true,
		'autoScale': true,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'titlePosition': 'inside',
		'centerOnScroll': true
	});

	$("a.fancybox_rel").fancybox({
		'width': 800,
		'height': 320,
		'overlayShow': true,
		'hideOnOverlayClick': true,
		'hideOnContentClick': false,
		'autoDimensions': false,
		'transitionIn': 'fade',
		'transitionOut': 'fade',
		'centerOnScroll': true
	});
	
	$("a.rpass").fancybox({
		'width': 500,
		'height': 320,
		'overlayShow': true,
		'hideOnOverlayClick': true,
		'hideOnContentClick': false,
		'autoDimensions': false,
		'transitionIn': 'fade',
		'transitionOut': 'fade',
		'centerOnScroll': true
	});
	
});

function checkSubmitSearch()
{
	return false;
}

/*
 * Muestra un alert y ejecuta la funcion
 */
function messageAndGo(str, onclick)
{
	jAlert(str, 'Compostadores', onclick);
}

/*
 * Muestra un alert
 */
function message(str)
{
	jAlert(str, 'Compostadores');
}

/*
 * Carga de combos con JSON
 */
function loadJCombo(slt, file, val, callback)
{
	slt.html("");
	//slt.attr("disabled", true);
	var options = '';
	
	$.getJSON(file, function(data) {
		$.each(data.items, function(i, item) {
			if(item) {
				if(item.name) {
					options += '<option value="' + item.id + '">' + item.name + '</option>';
				}
			}
		});
		slt.html(options);
		slt.val(val);
		slt.attr("disabled", false);
		
		if(typeof callback == "function") {
			callback.apply(this);
		}
	});
}

function todo(str)
{
	message("@todo: " + str);
}

/*
 * urlencode como el de PHP
 */
function urlencode(str)
{
	str = (str+'').toString();
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

/*
 * number_format como el de PHP
 */
function number_format(number, decimals, dec_point, thousands_sep)
{
   var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

/*
 * Uso:
 * 
 * function foo(arg1, arg2, arg3, ...) {
 *     debugParamsFunction(arguments);
 *     ...
 * }
 */
function debugParamsFunction(args)
{
	var outFunc = args.callee.toString();
	outFunc = outFunc.substr('function '.length);
	outFunc = outFunc.substr(0, outFunc.indexOf('('));
	outFunc += " (";
	for(var n=0; n<args.length; n++) {
		if(typeof args[n] == "string") outFunc += "'";
		outFunc += args[n];
		if(typeof args[n] == "string") outFunc += "'";
		if(n < (args.length-1)) {
			outFunc += ", ";
		}
	}
	outFunc += ");";
	alert(outFunc);
}

function base64_encode (data)
{
    // Encodes string using MIME base64 algorithm  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/base64_encode
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    // data = this.utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
 
        bits = o1<<16 | o2<<8 | o3;
 
        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;
 
        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
 
    return enc;
}

var OK = 1;
var KO = 0;
