/*
------------------------------------------------------------------

Common Kinkama JSLib
by Nordine Ghachi
from Les Tanukis
http://www.lestanukis.com
last update : 12-04-2007

------------------------------------------------------------------
*/
function kinkama(){ return "beta"; }

function chg_type(sexe){
	getObject('brun').src="../js/types/"+sexe+"/brun.gif";
	getObject('blond').src="../js/types/"+sexe+"/blond.gif";
	getObject('roux').src="../js/types/"+sexe+"/roux.gif";
	getObject('black').src="../js/types/"+sexe+"/black.gif";
	getObject('chauve').src="../js/types/"+sexe+"/chauve.gif";
}

// Fonctions de préload
function load() {
	if (document.images) {
		this.length=load.arguments.length;
		for (var i=0;i<this.length;i++) {
			this[i+1]=new Image();
			this[i+1].src=load.arguments[i];
		}
	}
}

function checkInt(champ){
	var chiffres = new RegExp("[0-9]");
	var verif;
	for(x = 0; x < champ.value.length; x++){
		verif = chiffres.test(champ.value.charAt(x));
		if(verif == false){champ.value = champ.value.substr(0,x) + champ.value.substr(x+1,champ.value.length-x+1); x--;}
	}
}

// function getPageHeight() inspired of getPageSize() function by Lokesh Dhakar - http://www.huddletogether.com
function getPageHeight(){
	var pageHeight;

	var yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
	}
	
	var windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	return pageHeight;
}

function getObject(idname){
	if (document.getElementById){
		return document.getElementById(idname);
	}else if (document.all){
		return document.all[idname];
	}else if (document.layers){
		return document.layers[idname];
	}else{
		return null;
	}
}

function setFullHeight(elem){
	pageHeight = getPageHeight();
	elemHeight = elem.style.height;
	elem.style.height = (elemHeight + pageHeight) + 'px';
}

function include_dom(script_filename) {
	var html_doc = document.getElementsByTagName('head').item(0);
	var js = document.createElement('script');
	js.setAttribute('language', 'javascript');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', script_filename);
	js.setAttribute('defer', 'defer');
	html_doc.appendChild(js);
	return false;
}

function include_css(script_filename) {
	var html_doc = document.getElementsByTagName('head').item(0);
	var css = document.createElement('link');
	css.setAttribute('rel','stylesheet');
	css.setAttribute('type','text/css');
	css.setAttribute('href',script_filename);
	html_doc.appendChild(css);
	return false;
}

var included_files = new Array();

function include_once(script_filename) {
    
	var type = script_filename.slice(-3);
	if (!in_array(script_filename, included_files)) {
		included_files[included_files.length] = script_filename;
		switch (type){
		case '.js':
			include_dom(script_filename);
			break;
		case 'css':
			include_css(script_filename);
			break;
		default:
			include_dom(script_filename);
			break;
		}
	}
}

function in_array(needle, haystack) {
	for (var i = 0; i < haystack.length; i++) {
		if (haystack[i] == needle) {
			return true;
		}
	}
	return false;
}

function countLines(element) {
	strtocount = element.value;
	cols = element.cols;
	var hard_lines = 1;
	var last = 0;
	while ( true ) {
		last = strtocount.indexOf("\n", last+1);
		hard_lines ++;
		if ( last == -1 ) break;
	}
	var soft_lines = Math.round(strtocount.length / (cols-1));
	var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
	if (hard) soft_lines = hard_lines;
	return soft_lines;
}

function keyhit(element, e) {
	var touche = (window.Event) ? e.which : e.keyCode;//pour savoir s'il s'agit de Msie ou de Netscape
	if(touche==13 || touche==8 || touche==0)
		element.rows = countLines(element);
}

function print_r( array, return_val ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://crestidg.com)
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
 
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if(obj instanceof Array) {
            str += "Array\n" + base_pad + "(\n";
            for(var key in obj) {
                if(obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString();
        };
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { str += pad_char; };
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if(return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
}

function explode( delimiter, string, limit ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function hide(block){ 
	document.getElementById(block).style.display = 'none';
}

function show(block){
	document.getElementById(block).style.display = 'block';
}

function displayWait(block){
	document.getElementById(block).innerHTML = '<div align="center"><img src="/media/loading.gif"/></div>';
}

function popUp(w,h,title,content) {
	if (!w) w = '200';
	if (!h) h = '200';
	if (!title) title = 'Pop-Up';
	if (!content) content = '';
	var top=(screen.height-h)/2;
	var left=(screen.width-w)/2;
	oFenetre = window.open(content,'Image','width='+w+',height='+h+',toolbar=no,scrollbars=no,resizable=yes,top='+top+',left='+left);
}

function getNavClient()
{
	datetoday = new Date();
	timenow= datetoday.getTime();
	datetoday.setTime(timenow);
	return datetoday.getHours();
}

/**
 * This function is call on load by FormManager::fillField and JSEventManager,
 * to check html widget wich were checked before the form submission.
 * 
 * jsonArr must look like that :
 * 
 * 'fieldType': 'radio_or_select_or...', 'fieldName' : 'fieldName', 'fieldVlue' : 'fieldValue' }
 * 
 * setSelectedSpecialFormWidget(
 *     {"career":{
 *         "fieldType":"simpleSelect",
 *         "fieldName":"career",
 *         "value":"ortho"
 *     },
 *     "state_deliver":{
 *     	   "fieldType":"simpleSelect",
 *         "fieldName":"state_deliver",
 *         "value":"fr"
 *     },
 *     ...
 * 
 * @param {Object} jsonArr
 */
function checkFormWidget( jsonArr )
{
	//console.debug(jsonArr);
	
	if( typeof jsonArr != "object" || jsonArr == "" )
		console.log( "MisMatch with setSelectedSpecialFormWidget params. Waiting for an array." );
	
	if( typeof jQuery !== "function" )
		console.log("Kinkama need jQuery to perform common task. Please, include-it ...");
	
	for( var i = 0 ; i< jsonArr.length ; i++ )
	{
		if ( typeof jsonArr[ i ] != 'undefined' )
		{
			//console.debug( jsonArr[ i ] );
			
			var formName = $("[name='"+jsonArr[0].fieldName+"']").closest("form").attr("name");
			//console.debug(formName);
			
			var v = jsonArr[ i ].value; //console.debug(f);
			var f = jsonArr[ i ].fieldName; //console.debug(v);
			
			switch( jsonArr[ i ].fieldType )
			{
				case "simpleRadio" :
				case "simpleCheckbox" :
					
					var  el = $("input[name='"+f+"']", document[formName] );
					
					el.each(function(i){
						var val = $(this).attr("value");
						if( val == v ) $(this).attr('checked', true);
					});

					break;
					
				case "simpleSelect" :
					
					$("[name='"+f+"']", document[formName] ).val(v);
					
					break;
					
				case "multipleSelect" :
					
					/**
					 * @todo
					 */
					
					/*var aValue =  jsonArr[ i ].fieldValue.split(',');
					for( var j = 0 ; j < aValue.length ; j ++ ){
						var allOption = $( "[name="+jsonArr[ i ].fieldName+"[]] > option");
						allOption.each( function (k) {
							if ($(this).attr('value') == aValue[ j ] ) $(this).attr('selected', 'selected');
						});
					}*/
					break;
				
				case "multipleCheckbox" :
					
					/**
					 * @todo
					 */
				
					/* var aValue =  jsonArr[ i ].fieldValue.split(',');
					//alert( aValue );
					for( var j = 0 ; j < aValue.length ; j ++ ){
						var allCheckbox = $( "[name="+jsonArr[ i ].fieldName+"[]]");
						alert( allCheckbox )
						allCheckbox.each( function(k){
							if( $(this).attr('value') == aValue[ j ] ) $(this).attr('checked',true);
						});
					}
					 */
					break;
			}
		}
		else continue;
	}
}

/**
 * Check a string with only figures and letter
 * 
 * @param (string) string to check
 * @return (string)
 */
function validateString( sString )
{
	var regExp = /[0-9][A-Za-z]/g; //contient au moins 1 chiffre /avec ou sans les '^'et '$' pareil
	
	if( regExp.test(sString) )
	{
		return true ;
	}
	else
	{
		return false ;
	}
}

function addslashes (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}

function strip_tags(html){
	 
	//PROCESS STRING
	if(arguments.length < 3) {
		html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
	} else {
		var allowed = arguments[1];
		var specified = eval("["+arguments[2]+"]");
		if(allowed){
			var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		} else{
			var regex='</?(' + specified.join('|') + ')\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		}
	}

	//CHANGE NAME TO CLEAN JUST BECAUSE 
	var clean_string = html;

	//RETURN THE CLEAN STRING
	return clean_string;
}

function arrayKeyOf ( array, search_value ) 
{
	for ( var i = 0 ; i < array.length ; i++ )
	{
		if ( array[i] == search_value ) break ;
	}
	return i ;
}

function replaceBC( text )
{
	var aToReplace = new RegExp("(\r\n|\r|\n)", "g" );
	text = text.replace( aToReplace , "<br/>" ) ;
	
	return text ;
}

/*
function nl2br( text )
{
	Retourchar  = String.fromCharCode(13) + String.fromCharCode(10);
	return text.replace( "<br/>" , "Retourchar" ) ;
}
*/


