/*
## vBegin
## 
## Copyright 2008, 2009, 2010 ECLYDRE <ewm@eclydre.fr>
## This file is part of Eclydre Web Manager.
## 
## Eclydre Web Manager is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## Eclydre Web Manager is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with Eclydre Web Manager.  If not, see <http://www.gnu.org/licenses/>.
## 
## This copyright notice MUST APPEAR in all copies of the script!  
## 
## Eclydre Web Manager v2.6.3
## Dateversion 2011-11-01
## File : ../core//js/inc_fct.js
## Changelogs : 
## v2.6.3 2011-11-01 Fixing snewpage on folder
## v2.5.2 2011-07-06 Adding image crop
## v2.5.1 2011-06-14 Adding undo functions
## v2.0.7 2010-11-08 Adding input focus/blur effect
## v2.0.6 2010-10-07 Adding nodrag
## v2.0.5 2010-10-04 Adding new page, new folder, waiting_animation()
## v2.0.4 2010-09-28 Adding drag & drop confirm
## v2.0.3 2010-09-27 Adding drag & drop support in saveBloc()
## v2.0.2 2010-09-25 Adding drag & drop support in list
## v2.0.1 2010-09-24 Adding drag & drop support
## ;
## vEnd
*/
if(typeof(ewm_admin) == "undefined") ewm_admin=0;
var msie = navigator.userAgent.indexOf('MSIE')>-1?1:0;
$(document).ready(
	function () {
		if(typeof $.fn.datePicker != 'undefined')
		{
			Date.format = 'yyyy-mm-dd 00:00:00';
			$('.datepicker').datePicker({clickInput:false,startDate:'1900-01-01'});
		}
		if(ewm_admin)
		{
			// ___ drag and drop dans les listes
			if(typeof $.fn.draggable != 'undefined')
			{
			//__ DRAG
				$(".tabentete").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
				$(".form_div_inline").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
				$(".draggable").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
			//__ DROP
				$(".tabentete,.form_td_lib_sstable,.form_div_inline").droppable({
				  tolerance: 'pointer',
				  hoverClass: 'drophover',
				  drop: function(event, ui) { 
					// on va tenter de simuler un couper/coller
					if(confirm(config_confirm_draganddrop)) ssaction( '', form_name, 'draganddrop|::'+(ui.draggable.parent().find('.move').html())+'|::'+($(this).parent().find('.paste').html()));
					else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
				  }
				});
				$(".trList1,.trList2").droppable({
				  tolerance: 'pointer',
				  hoverClass: 'drophover',
				  drop: function(event, ui) { 
					// on va tenter de simuler un couper/coller
					if(confirm(config_confirm_draganddrop)) ssaction( '', form_name, 'draganddrop|::'+(ui.draggable.parent().parent().find('.move').html())+'|::'+($(this).find('.paste').html()));
					else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
				  }
				});
				// plan du site
				$('.file').draggable({ opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
				$('.folder').draggable({ opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
				$('.file').droppable({
				  tolerance: 'pointer',
				  accept: '.file,.snewpage',
				  hoverClass: 'drophover',
				  drop: function(event, ui) { 
					// on va tenter de simuler un couper/coller
					if(ui.draggable.hasClass('snewpage'))
					{
						// new page
						nompage = '';
						nbnom = 0;
						for(i=1;i<6;i++)
						{
							if(document.stoolbox.elements['n_page_'+i].value)
							{
								nompage = document.stoolbox.elements['n_page_'+i].value+(nompage?'/#/':'')+nompage;
								nbnom++;
							}
						}
						if(!nompage) nompage = 'new page';
						ssaction = $(this).find('.insert').html()+'|nom|'+nompage;
						waiting_animation();
						window.location.href = '?ssaction='+escape((config_charset=='UTF-8'?utf8encode(ssaction):ssaction));
					}
					else if(confirm(config_confirm_draganddrop)) 
					{
						waiting_animation();
						window.location.href = '?ssaction='+escape('draganddrop|::'+(ui.draggable.find('.move').html())+'|::'+($(this).find('.paste').html()));
					}
					else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
				 }});
				$('.folder').droppable({
				  tolerance: 'pointer',
				  accept: '.file,.folder,.snewpage,.snewrub',
				  hoverClass: 'drophover',
				  drop: function(event, ui) { 
					// on va tenter de simuler un couper/coller
					// on regarde si on colle une page 
					if(ui.draggable.hasClass('snewpage'))
					{
						// new page
						nompage = '';
						nbnom = 0;
						for(i=1;i<6;i++)
						{
							if(document.stoolbox.elements['n_page_'+i].value)
							{
								nompage = document.stoolbox.elements['n_page_'+i].value+(nompage?'/#/':'')+nompage;
								nbnom++;
							}
						}
						if(!nompage) nompage = 'new page';
						ssaction = $(this).find('.insertpage').html()+'|nom|'+nompage;
						waiting_animation();
						window.location.href = '?ssaction='+escape((config_charset=='UTF-8'?utf8encode(ssaction):ssaction));
					}
					else if(ui.draggable.hasClass('snewrub'))
					{
						// new arbo
						nomarbo = '';
						nbarbo = 0;
						for(i=1;i<6;i++)
						{
							if(document.stoolbox.elements['n_arbo_'+i].value)
							{
								nomarbo = document.stoolbox.elements['n_arbo_'+i].value+(nomarbo?'/#/':'')+nomarbo;
								nbarbo++;
							}
						}
						if(!nomarbo) nomarbo = 'new folder';
						ssaction = $(this).find('.insert').html()+'|nom|'+nomarbo;
						waiting_animation();
						window.location.href = '?ssaction='+escape((config_charset=='UTF-8'?utf8encode(ssaction):ssaction));
					}
					else
					{
						if(confirm(config_confirm_draganddrop))
						{
							waiting_animation();
							if(ui.draggable.find('.move').html().substring(0, 11)=='move|c_page') window.location.href = '?ssaction='+escape('draganddrop|::'+(ui.draggable.find('.move').html())+'|::'+($(this).find('.pastepage').html()));
							else window.location.href = '?ssaction='+escape('draganddrop|::'+(ui.draggable.find('.move').html())+'|::'+($(this).find('.paste').html()));
						}
						else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
					}
				 }});
				$('.folderin').droppable({
				  tolerance: 'pointer',
				  accept: '.folder,.snewrub',
				  hoverClass: 'drophoverin',
				  drop: function(event, ui) { 
					if(ui.draggable.hasClass('snewrub'))
					{
						// new arbo
						nomarbo = '';
						nbarbo = 0;
						for(i=1;i<6;i++)
						{
							if(document.stoolbox.elements['n_arbo_'+i].value)
							{
								nomarbo = document.stoolbox.elements['n_arbo_'+i].value+(nomarbo?'/#/':'')+nomarbo;
								nbarbo++;
							}
						}
						if(!nomarbo) nomarbo = 'new folder';
						ssaction = $(this).find('.insert').html()+'|nom|'+nomarbo;
						waiting_animation();
						window.location.href = '?ssaction='+escape((config_charset=='UTF-8'?utf8encode(ssaction):ssaction));
					}
					else
					{
						if(confirm(config_confirm_draganddrop)) 
						{
							waiting_animation();
							window.location.href = '?ssaction='+escape('draganddrop|::'+(ui.draggable.find('.move').html())+'|::'+($(this).find('.paste').html()));
						}
						else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
					}
				 }});
				$(".nodrag").draggable("disable");
			}
		}
	}
);

function GL_checkBrowser(){
	this.dom= (document.getElementById);
	this.op=this.opera= (navigator.userAgent.indexOf("Opera")>-1);
	this.konq=  (navigator.userAgent.indexOf("Konq")>-1);
	this.ie4= (document.all && !this.dom && !this.op && !this.konq);
	this.ie5= (document.all && this.dom && !this.op && !this.konq);
	this.ns4= (document.layers && !this.dom && !this.konq);
	this.ns5= (!document.all && this.dom && !this.op && !this.konq);
	this.ns6= (this.ns5);
	this.bw=  (this.ie4 || this.ie5 || this.ns4 || this.ns6 || this.op || this.konq);
	return this;
}
bw= new GL_checkBrowser();

	//Returns css
function GL_getObjCss(obj){								
	return bw.dom? document.getElementById(obj).style:bw.ie4?document.all[obj].style:bw.ns4?document.layers[obj]:0;
};
function jsStyle(obj){								
	return bw.dom? document.getElementById(obj).style:bw.ie4?document.all[obj].style:bw.ns4?document.layers[obj]:0;
};
function jsObj(obj){								
	return bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
};

function showDiv(id)
{
	etat = GL_getObjCss(id).display;
	switch(etat)
	{
		case "none": GL_getObjCss(id).display="block"; break;
		case "block": GL_getObjCss(id).display="none"; break;
	}
}

function showDivForm(id, inputH, withajax, ajaxpath)
{
	var numform = 0;
	while(document.forms[numform].name.substring(0, 2)!='f_') numform++;
	etat = GL_getObjCss(id).display;
	switch(etat)
	{
		case "none": 
			GL_getObjCss(id).display="block"; document.forms[numform].elements[inputH].value='0'; 
			if(withajax == 'ajax' && ajaxpath)
			{
				var nb = 0;
				$('#'+id).each(function(){
					nb++;
					div = $(this);
				});
				if(!nb)
				{
					$('div').each(function(){
						if($(this).attr('id')==id)
						{
							nb++;
							div = $(this);
						}
					});
				}
				if(nb && div.html()=='') 
				{
					div.html('<img src="load.gif" width="36" height="36" alt="loading"/>');
					$.ajax({ type: "get", dataType:"html", url: ajaxpath, data: "bloc="+id, 
						success: function(content){
							div.html(content);/*alert( content);*/
							$(".inputRequired select").each(function () {
								if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
								else  $(this).removeClass('requiredEmpty');
							   });
							$(".inputRequired input").each(function () {
								if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
								else  $(this).removeClass('requiredEmpty');
							   });
							$(".inputRequired textarea").each(function () {
								if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
								else  $(this).removeClass('requiredEmpty');
							   });
							$(".withchelp").mouseenter(function() {
								var tClass = $(this).attr('class').split(' ');
								for( var i=0; i<tClass.length && tClass[i].substring(0, 5)!='chelp'; i++);
								if(i<tClass.length && tClass[i]!=contextual_help)
								{
									contextual_help = tClass[i];
									var chelp_key = tClass[i];
									if(chelp[ chelp_key]) $("#contextual_help").html(chelp[ chelp_key]);
									else
									{
										chelp[chelp_key] = 'loading...';
										$.ajax({ type: "get", dataType:"html", url: root_path+"administrator/contextual_help.php", data: "code="+escape(chelp_key), 
											success: function(content){
												$("#contextual_help").html(content);
												chelp[chelp_key] = content;
											}
										});
									}
								}
							});
							$("input,select,textarea").focus(function(){$(this).addClass("inputfocused")});
							$("input,select,textarea").blur(function(){$(this).removeClass("inputfocused")});
							$(".inputRequired input").focus(function(){
								g_input_focus = $(this).attr('name');
								checkRequiredField( 'input', $(this).attr('name'));
							});
							$(".inputRequired input").blur(function(){
								checkRequiredField( 'input', $(this).attr('name'));
							});
							$(".inputRequired select").focus(function(){
								g_input_focus = $(this).attr('name');
								checkRequiredField( 'select', $(this).attr('name'));
							});
							$(".inputRequired select").blur(function(){
								checkRequiredField( 'select', $(this).attr('name'));
							});
							$(".inputRequired textarea").focus(function(){
								g_input_focus = $(this).attr('name');
								checkRequiredField( 'textarea', $(this).attr('name'));
							});
							$(".inputRequired textarea").blur(function(){
								checkRequiredField( 'textarea', $(this).attr('name'));
							});
							$('.datepicker').datePicker({clickInput:false,startDate:'1900-01-01'});							
							if(typeof $.fn.draggable != 'undefined')
							{
							//__ DRAG
								$(".tabentete").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
								$(".form_div_inline").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
								$(".draggable").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
							//__ DROP
								$(".tabentete,.form_td_lib_sstable,.form_div_inline").droppable({
								  tolerance: 'pointer',
								  hoverClass: 'drophover',
								  drop: function(event, ui) { 
									// on va tenter de simuler un couper/coller
									if(confirm(config_confirm_draganddrop)) ssaction( '', form_name, 'draganddrop|::'+(ui.draggable.parent().find('.move').html())+'|::'+($(this).parent().find('.paste').html()));
									else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
								  }
								});
								$(".trList1,.trList2").droppable({
								  tolerance: 'pointer',
								  hoverClass: 'drophover',
								  drop: function(event, ui) { 
									// on va tenter de simuler un couper/coller
									if(confirm(config_confirm_draganddrop)) ssaction( '', form_name, 'draganddrop|::'+(ui.draggable.parent().parent().find('.move').html())+'|::'+($(this).find('.paste').html()));
									else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
								  }
								});
								$(".nodrag").draggable("disable");
								$('textarea.grippieresizable:not(.processed)').TextAreaResizer();
								$('iframe.grippieresizable:not(.processed)').TextAreaResizer();
							}
							
							}});
				}
			}
			break;
		case "block": GL_getObjCss(id).display="none"; document.forms[numform].elements[inputH].value='1'; break;
	}
	//alert(document.forms[0].elements[inputH].value);
}

function confirmation(text, wheretogo)
{
	if(confirm(text.replace('<br>', '\n'))) window.location.href= wheretogo;
	else waiting_stop();
}

function ssaction(text, formname, val, opmult)
{
	if(!text || (text && confirm(text))) 
	{
		document.forms[formname].ssaction.value = val;
		pos = document.documentElement.scrollTop;
		document.forms[formname].posTop.value= pos;
		if(isDefined('isRichText')) 
		{
			try {
				updateRTEs();
			} catch(e) {}
		}
		// on sauve les champs CodeMirror
		for (var i = 0; i < tCodeMirror.length; i++) /*if(tCodeMirrorElements[i]!='deleted')*/ tCodeMirror[i].save();
		if(opmult) document.forms[formname].opmult.value = document.forms[formname].elements[opmult].value;
		var delSel = 0;
		if(document.forms[formname].elements["sel[]"])
		{
			 sz = document.forms[formname].elements["sel[]"].length;
			 for(i=0; i<sz; i++) if(document.forms[formname].elements["sel[]"][i].checked) delSel++;
			 if(delSel)
			 {
			 	if(confirm("warning !\n\nmarked to delete : "+delSel)) delSel = 0;
			 }
		}
		if(!delSel) 
		{
			waiting_animation( '../');
			document.forms[formname].submit();
		}
	}
}

function ajouteOption(formname, fieldname, stchaine, stid)
{
		var nb = document.forms[formname].elements[fieldname].options.length;
		//alert(nb);
		//var stchaine = new String('<?=addslashes($val)?>');
		//var stid = new String('<?=$id?>');
		//no = new Option( stchaine, stid, 0, 1);
		no = new Option( stchaine, stid, 0, 1);
		document.forms[formname].elements[fieldname].options[nb]= no;
		document.forms[formname].elements[fieldname].selectedIndex= nb;
}

function jsOpen(page, title, params)
{
	var w = window.open(page, title, params);
	w.focus();
}

function showDefault(div)
{
	jsStyle(div).display = 'block';
	if(tempX<850)
	{
		jsStyle(div).top = (tempY-20)+'px';
		jsStyle(div).left = (tempX+10)+'px';
	}
	else
	{
		jsStyle(div).top = (tempY-20)+'px';
		jsStyle(div).left = (tempX-160)+'px';
	}
}


//___________________________positionne un div par rapport  la souris
function showMouseDiv(div, dX, dY)
{
	jsStyle(div).display = 'block';
	jsStyle(div).top = (tempY+dY)+'px';
	jsStyle(div).left = (tempX+dX)+'px';
}

// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false

if(ewm_admin)
{
	// If NS -- that is, !IE -- then set up for mouse capture
	if (!IE) document.captureEvents(Event.MOUSEMOVE)

	// Set-up to use getMouseXY function onMouseMove
	if(!isDefined('noMouseMoveEvent')) noMouseMoveEvent = 0;
	if(!noMouseMoveEvent) document.onmousemove = getMouseXY;

	// Temporary variables to hold mouse x-y pos.s
	var tempX = 0
	var tempY = 0
}

// Main function to retrieve mouse x-y pos.s


function getMouseXY(e) {

  if (IE) { // grab the x-y pos.s if browser is IE
  tempX = event.clientX + document.documentElement.scrollLeft;
  tempY = event.clientY + document.documentElement.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  return true;
}



var charArray = new Array(
	' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-',
	'.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
	'<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
	'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
	'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e',
	'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
	't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '', 'Ç', 'ü',
	'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å',
	'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', 'ø', '£', 'Ø',
	'×', 'ƒ', 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '®', '¬', '½',
	'¼', '¡', '«', '»', '_', '_', '_', '¦', '¦', 'Á', 'Â', 'À', '©', '¦',
	'¦', '+', '+', '¢', '¥', '+', '+', '-', '-', '+', '-', '+', 'ã', 'Ã',
	'+', '+', '-', '-', '¦', '-', '+', '¤', 'ð', 'Ð', 'Ê', 'Ë', 'È', 'i',
	'Í', 'Î', 'Ï', '+', '+', '_', '_', '¦', 'Ì', '_', 'Ó', 'ß', 'Ô', 'Ò',
	'õ', 'Õ', 'µ', 'þ', 'Þ', 'Ú', 'Û', 'Ù', 'ý', 'Ý', '¯', '´', '­', '±',
	'_', '¾', '¶', '§', '÷', '¸', '°', '¨', '·', '¹', '³', '²', '_', ' ');

var hex_digits = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
		'A', 'B', 'C', 'D', 'E', 'F');


function charToByte(c)
{
	var i;
	for(i=0; i < charArray.length; i++) {
		if(c == charArray[i]) return i+32;
	}
	return 0;
}

function byteToChar(n)
{
	if(n < 32 || n > 255) return " ";
	return charArray[n-32];
}

function byteToHex(n)
{
	return hex_digits[(n >> 4) & 0xf] + hex_digits[n & 0xf];
}

function byteToBin(n)
{
	var ret_str = "";
	var i;
	for(i=7; i>=0; i--) {
		ret_str += (n >> i) & 1;
	}
	return ret_str;
}



function clean_numstr(raw_str, base)
{
	var ret_str = "";
	var c = "";
	var i;
	for(i=0; i < raw_str.length; i++) {
		c = raw_str.charAt(i);
		if(c == "0" || parseInt(c, base) > 0) {
			ret_str += c;
		}
	}
	return ret_str;
}

function isNothing(str, theForm, form_bit)
{
	if(str == "") {
		alert("This field evaluates to nothing!");
		return false;
	}
	eval(form_bit);
	return true;
}



function hex_from_dec(theForm)
{
	var dec_str = clean_numstr(theForm.dec.value, 10);
	var delimiter = theForm.delimiter.value;
	var hex_str = "";
	var num_str = "";
	var i = 0, n;

	while(i < dec_str.length) {
		n = 0;
		if(i > 0) hex_str += delimiter;
		for(; i < dec_str.length && (n < 25 || (n == 25 && dec_str.charAt(i) < 6)); i++) {
			n *= 10;
			n += parseInt(dec_str.charAt(i));
		}
		hex_str += byteToHex(n);
	}
	return isNothing(hex_str, theForm, "theForm.hex.value = str");
}

function chars_from_hex(theForm)
{
	var hex_str = clean_numstr(theForm.hex.value, 16);
	var char_str = "";
	var num_str = "";
	var i;
	for(i=0; i < hex_str.length; i+=2)
		char_str += byteToChar(parseInt(hex_str.substring(i, i+2), 16));
	return isNothing(char_str, theForm, "theForm.chars.value = str");
}

function hex_from_chars(theForm)
{
	var char_str = theForm.chars.value;
	var delimiter = theForm.delimiter.value;
	var hex_str = "";
	var i, n;
	for(i=0; i < char_str.length; i++) {
		n = charToByte(char_str.charAt(i));
		if(n != 0) {
			if(i > 0) hex_str += delimiter;
			hex_str += byteToHex(n);
		}
	}
	return isNothing(hex_str, theForm, "theForm.hex.value = str");
}

function dec_from_hex(theForm)
{
	var hex_str = clean_numstr(theForm.hex.value, 16);
	var delimiter = theForm.delimiter.value;
	var dec_str = "";
	var dec_byte = "";
	var i;
	for(i=0; i < hex_str.length-1; i+=2) {
		if(i > 0) dec_str += delimiter;
		dec_str += parseInt(hex_str.substring(i, i+2), 16);
	}
	return isNothing(dec_str, theForm, "theForm.dec.value = str");
}

function bin_from_hex(theForm)
{
	var hex_str = clean_numstr(theForm.hex.value, 16);
	var delimiter = theForm.delimiter.value;
	var bin_str = "";
	var bin_byte = "";
	var i;
	for(i=0; i < hex_str.length-1; i+=2) {
		if(i > 0) bin_str += delimiter;
		bin_str += byteToBin(parseInt(hex_str.substring(i, i+2), 16));
	}
	return isNothing(bin_str, theForm, "theForm.bin.value = str");
}

function hex_from_bin(theForm)
{
	var delimiter = theForm.delimiter.value;
	var bin_str = clean_numstr(theForm.bin.value, 2);
	var hex_str = "";
	var i;

	for (i=0; i < bin_str.length-7; i+=8) {
		if(i > 0) hex_str += delimiter;
		hex_str += byteToHex(parseInt(bin_str.substring(i, i+8), 2));
	}
	return isNothing(hex_str, theForm, "theForm.hex.value = str");
}

function from_dec(theForm)
{
	if (hex_from_dec(theForm)) {
		bin_from_hex(theForm);
		chars_from_hex(theForm);
	}
}

function from_hex(theForm)
{
	if(bin_from_hex(theForm)){
		dec_from_hex(theForm);
		chars_from_hex(theForm);
	}
}

function from_char(theForm)
{
	if(hex_from_chars(theForm)) {
		bin_from_hex(theForm);
		dec_from_hex(theForm);
	}
}

function from_bin(theForm)
{
	if(hex_from_bin(theForm)) {
		dec_from_hex(theForm);
		chars_from_hex(theForm);
	}
}

function isDefined(variable)
{
return eval('(typeof('+variable+') != "undefined");');
}

//________________________________________ scroll un div
var doscroll = 1;
function scrollzone(iddiv, decal)
{
	var t = isDefined(jsObj(iddiv).scrollTop)?jsObj(iddiv).scrollTop:0;
	
	jsObj(iddiv).scrollTop = t+decal;
	if(doscroll) setTimeout('scrollzone("'+iddiv+'", '+decal+')', 50);
}
function initscroll(iddiv, height)
{
	var h = jsObj('scroll'+iddiv).scrollHeight;
	//alert(h+' '+height+' '+jsObj('scroll'+iddiv).scrollHeight);
	if(h<=height)
	{
		jsStyle('scrollup'+iddiv).display = 'none';
		jsStyle('scrolldown'+iddiv).display = 'none';
	}
}

// ______________________ QueryString

function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}
var q_GET = new Querystring(window.location.search.substring(1));

// __________________GESTION DES COOKIES

function EcrireCookie(nom, valeur)
{
	var argv=EcrireCookie.arguments;
	var argc=EcrireCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}

function getCookieVal(offset)
{
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function LireCookie(nom)
{
	var arg=nom+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen)
	{
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	
	}
	return null;
}

function setFlashWidth(divid, newW){
	document.getElementById(divid).style.width = newW+"px";
}
function setFlashHeight(divid, newH){
	document.getElementById(divid).style.height = newH+"px";		
}
function setFlashSize(divid, newW, newH){
	setFlashWidth(divid, newW);
	setFlashHeight(divid, newH);
}
function canResizeFlash(){
	var ua = navigator.userAgent.toLowerCase();
	var opera = ua.indexOf("opera");
	if( document.getElementById ){
		if(opera == -1) return true;
		else if(parseInt(ua.substr(opera+6, 1)) >= 7) return true;
	}
	return false;
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function rechercher(text, wheretogo, pattern, getParam)
{
	$("select").hide();
	$("object").hide();
	$("embed").hide();
	$("#window").html('');
	$("#overlay").show();
	$("#window").css( "width", "350px");
	$("#window").css( "height", "150px");
	$("#window").css( "left",(($(window).width()-400)/2)+"px");
	$("#window").css( "top", (($(window).height()-400)/2)+"px");
	$("#window").show();

	$.ajax({type: "get", dataType:"html", url: "jssearch.php", data: "text=" + escape(text) + "&wheretogo=" + escape(wheretogo) + "&pattern=" + escape(pattern) + "&getParam=" + escape(getParam), success: function(content){$("#window").html(content);}}); 
}

function jsprompt(text, wheretogo, callback, defaut)
{
	$("select").hide();
	$("object").hide();
	$("embed").hide();
	$("#window").html('');
	$("#overlay").show();
	$("#window").css( "width", "350px");
	$("#window").css( "height", "150px");
	$("#window").css( "left",(($(window).width()-400)/2)+"px");
	$("#window").css( "top", (($(window).height()-400)/2)+"px");
	$("#window").show();

	$.ajax({type: "get", dataType:"html", url: "jsprompt.php", data: "text=" + escape(text) + "&wheretogo=" + escape(wheretogo) + "&callback=" + escape(callback) + "&defaut=" + escape(defaut), success: function(content){$("#window").html(content);}}); 
}

function xliff_form( categ, table, id)
{
	$("select").hide();
	$("object").hide();
	$("embed").hide();
	$("#window").html('');
	$("#overlay").show();
	$("#window").css( "width", "300px");
	$("#window").css( "height", "250px");
	$("#window").css( "left",(($(window).width()-300)/2)+"px");
	$("#window").css( "top", (($(window).height()-200)/2)+"px");
	$("#window").show();

	$.ajax({type: "get", dataType:"html", url: "ajax_xliff_form.php", data: "categ=" + escape(categ)+"&table=" + escape(table)+"&id=" + escape(id), success: function(content){$("#window").html(content);}}); 
}


//_______________________________

var g_input_focus = '';
function checkRequiredField( tag, name)
{
	var input = $(".inputRequired "+tag+"[name='"+name+"']");
	var val = input.attr('value');
	if(!val || val=='0')	input.addClass('requiredEmpty');
	else input.removeClass('requiredEmpty');
	if(g_input_focus==name) setTimeout( "checkRequiredField('"+tag+"', '"+name+"')", 1000);
}

if(ewm_admin)
{
	$(document).ready(function(){
		$("input,select,textarea").focus(function(){$(this).addClass("inputfocused")});
		$("input,select,textarea").blur(function(){$(this).removeClass("inputfocused")});
		$(".inputRequired select").each(function () {
			if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
			else  $(this).removeClass('requiredEmpty');
		   });
		$(".inputRequired input").each(function () {
			if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
			else  $(this).removeClass('requiredEmpty');
		   });
		$(".inputRequired textarea").each(function () {
			if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
			else  $(this).removeClass('requiredEmpty');
		   });

		$(".inputRequired input").focus(function(){
			g_input_focus = $(this).attr('name');
			checkRequiredField( 'input', $(this).attr('name'));
		});
		$(".inputRequired input").blur(function(){
			checkRequiredField( 'input', $(this).attr('name'));
		});
		$(".inputRequired select").focus(function(){
			g_input_focus = $(this).attr('name');
			checkRequiredField( 'select', $(this).attr('name'));
		});
		$(".inputRequired select").blur(function(){
			checkRequiredField( 'select', $(this).attr('name'));
		});
		$(".inputRequired textarea").focus(function(){
			g_input_focus = $(this).attr('name');
			checkRequiredField( 'textarea', $(this).attr('name'));
		});
		$(".inputRequired textarea").blur(function(){
			checkRequiredField( 'textarea', $(this).attr('name'));
		});
		$(".withchelp").mouseenter(function() {
			var tClass = $(this).attr('class').split(' ');
			for( var i=0; i<tClass.length && tClass[i].substring(0, 5)!='chelp'; i++);
			if(i<tClass.length && tClass[i]!=contextual_help)
			{
				contextual_help = tClass[i];
				var chelp_key = tClass[i];
				if(chelp[ chelp_key]) $("#contextual_help").html(chelp[ chelp_key]);
				else
				{
					chelp[chelp_key] = 'loading...';
					$.ajax({ type: "get", dataType:"html", url: root_path+"administrator/contextual_help.php", data: "code="+escape(chelp_key), 
						success: function(content){
							$("#contextual_help").html(content);
							chelp[chelp_key] = content;
						}
					});
				}
			}
		});
		$(window).scroll(function () { 
			  topscroll = document.documentElement.scrollTop; 
			  if(topscroll>90) $("#divTools").css('top', '10px');
			  else $("#divTools").css('top', (90-topscroll)+'px');
			});
		$("#contextual_help").dblclick(function(){
			if($(this).css('width')!='600px') $(this).css('width', '600px');
			else $(this).css('width', '160px');
		});
		/*$("#contextual_help").mouseenter(function(){
			$(this).css('width', '600px');
		});
		$("#contextual_help").mouseout(function(){
			$(this).css('width', '160px');
		});*/
	});
}
//_______________________________

function waiting_animation( root_path) 
{
	$("select").hide();
	$("object").hide();
	$("embed").hide();
	$("#window").html('<img src="'+root_path+'administrator/images/waiting_animation.gif" width="52" height="52" alt="waiting" class="waiting_animation"/>');
	$("#overlay").show();
	$("#window").css( "width", "200px");
	$("#window").css( "height", "150px");
	$("#window").css( "left",(($(window).width()-319)/2)+"px");
	$("#window").css( "top", (($(window).height()-305)/2)+"px");
	$("#window").show();
}

function waiting_stop( ) 
{
	$("select").show();
	$("object").show();
	$("embed").show();
	$("#overlay").hide();
	$("#window").hide();
}

//_______________________________ saveBloc, sauve le bloc d'admin en cours en Ajax

function saveBloc( fDIV, fForm, fTable, fId)
{
	nb = document.forms[ fForm].elements.length;
	pattern = 'r['+fTable+']['+fId+']';
	szpattern = pattern.length;
	params = '';
	try {
		updateRTEs();
	} catch(e) {}
	for (var i = 0; i < tCodeMirror.length; i++) tCodeMirror[i].save();
	for( i=0 ; i<nb; i++)
	{
		input = document.forms[ fForm].elements[ i];
		if(input && input.name.substring( 0, szpattern)==pattern) 
		{
			var type = input.type;
			if (!input.type)	type="radio";
			var value="";
			switch(type)	{
				case "text":
				case "password":
				case "hidden":
				case "textarea":
					//__ on cherche un code mirror et on le retire
					/*for (var k = 0; k < tCodeMirror.length; k++) 
					{
						if( input.name==tCodeMirrorElements[k])
						{
							tCodeMirror[k].toTextArea();
							tCodeMirrorElements[k] = 'deleted';
						}
					}*/
					//__
					value = input.value;
					params += '&'+input.name+'='+escape((config_charset=='UTF-8'?utf8encode(value):value));
				break;
				case "select-one":
					if (input.selectedIndex>=0)	{
						value = input.options[input.selectedIndex].value;
						params += '&'+input.name+'='+escape( (config_charset=='UTF-8'?utf8encode(value):value));
					}
				break;
				case "select-multiple":
					var l=input.length;
					for (a=0;a<l;a++)	{
						if (input.options[a].selected)	{
							 value = input.options[a].value;
				  			 params += '&'+input.name+'[]='+escape( (config_charset=='UTF-8'?utf8encode(value):value));
						}
					}
				break;
				case "radio":
					var l=input.length;
					if(l>0)
					{
						for (a=0; a<l;a++)	{
							if (input[a].checked)	{
								value = input[a].value;
							}
						}
						params += '&'+input.name+'='+escape( (config_charset=='UTF-8'?utf8encode(value):value));
					}
					else 
					{
						if(input.checked) 
						{
							value = input.value;
							params += '&'+input.name+'='+escape( (config_charset=='UTF-8'?utf8encode(value):value));
						}
					}
				break;
			}
			//alert(input.name+' '+type+' '+escape( value));
			//params += '&'+input.name+'='+escape( value);
		}
	}
	if(params)
	{
		//alert(params);
		if(fDIV)
		{
			var nb = 0;
			$('#'+fDIV).each(function(){
				nb++;
				div = $(this);
			});
			if(!nb)
			{
				$('div').each(function(){
					if($(this).attr('id')==fDIV)
					{
						nb++;
						div = $(this);
					}
				});
			}
			if(div.attr('id')==fDIV) 
			{
				div.html('<img src="load.gif" width="36" height="36" alt="loading"/>');
				
				$.ajax({ type: "post", dataType:"html", url: root_path+'administrator/ajax_savebloc.php', data: 'action=save&form='+escape(fForm)+'&divBloc='+escape(fDIV)+params, 
					success: function(content){
						div.html(content);
						$(".inputRequired select").each(function () {
							if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
							else  $(this).removeClass('requiredEmpty');
						   });
						$(".inputRequired input").each(function () {
							if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
							else  $(this).removeClass('requiredEmpty');
						   });
						$(".inputRequired textarea").each(function () {
							if(!$(this).attr('value') || $(this).attr('value')=='0') $(this).addClass('requiredEmpty');
							else  $(this).removeClass('requiredEmpty');
						   });
					
						$("input,select,textarea").focus(function(){$(this).addClass("inputfocused")});
						$("input,select,textarea").blur(function(){$(this).removeClass("inputfocused")});
						$(".inputRequired input").focus(function(){
							g_input_focus = $(this).attr('name');
							checkRequiredField( 'input', $(this).attr('name'));
						});
						$(".inputRequired input").blur(function(){
							checkRequiredField( 'input', $(this).attr('name'));
						});
						$(".inputRequired select").focus(function(){
							g_input_focus = $(this).attr('name');
							checkRequiredField( 'select', $(this).attr('name'));
						});
						$(".inputRequired select").blur(function(){
							checkRequiredField( 'select', $(this).attr('name'));
						});
						$(".inputRequired textarea").focus(function(){
							g_input_focus = $(this).attr('name');
							checkRequiredField( 'textarea', $(this).attr('name'));
						});
						$(".inputRequired textarea").blur(function(){
							checkRequiredField( 'textarea', $(this).attr('name'));
						});
						$(".withchelp").mouseenter(function() {
							var tClass = $(this).attr('class').split(' ');
							for( var i=0; i<tClass.length && tClass[i].substring(0, 5)!='chelp'; i++);
							if(i<tClass.length && tClass[i]!=contextual_help)
							{
								contextual_help = tClass[i];
								var chelp_key = tClass[i];
								if(chelp[ chelp_key]) $("#contextual_help").html(chelp[ chelp_key]);
								else
								{
									chelp[chelp_key] = 'loading...';
									$.ajax({ type: "get", dataType:"html", url: root_path+"administrator/contextual_help.php", data: "code="+escape(chelp_key), 
										success: function(content){
											$("#contextual_help").html(content);
											chelp[chelp_key] = content;
										}
									});
								}
							}
						});
						$('.datepicker').datePicker({clickInput:false,startDate:'1900-01-01'});							
						if(typeof $.fn.draggable != 'undefined')
						{
						//__ DRAG
							$(".tabentete").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
							$(".form_div_inline").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
							$(".draggable").draggable({axis:'y', opacity: 0.50, revert: 'invalid', scroll: true, zIndex: 999 });
						//__ DROP
							$(".tabentete,.form_td_lib_sstable,.form_div_inline").droppable({
							  tolerance: 'pointer',
							  hoverClass: 'drophover',
							  drop: function(event, ui) { 
								// on va tenter de simuler un couper/coller
								if(confirm(config_confirm_draganddrop)) ssaction( '', form_name, 'draganddrop|::'+(ui.draggable.parent().find('.move').html())+'|::'+($(this).parent().find('.paste').html()));
								else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
							  }
							});
							$(".trList1,.trList2").droppable({
							  tolerance: 'pointer',
							  hoverClass: 'drophover',
							  drop: function(event, ui) { 
								// on va tenter de simuler un couper/coller
								if(confirm(config_confirm_draganddrop)) ssaction( '', form_name, 'draganddrop|::'+(ui.draggable.parent().parent().find('.move').html())+'|::'+($(this).find('.paste').html()));
								else { ui.draggable.css('top',0); ui.draggable.css('left',0); }
							  }
							});
							$(".nodrag").draggable("disable");
						}
						
						}});
				
			}
		}
		else 
		{
			waiting_animation( root_path);
			document.forms[ fForm].submit();
		}
	}
}

function utf8encode(string) 
{
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < string.length; n++) {

		var c = string.charCodeAt(n);

		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}

	}

	return utftext;
}

function mailto( nom, domaine, ext)
{
	window.location.href= 'mailto:'+nom+'@'+domaine+'.'+ext;
}

function jsUNDO( table, id, field, form) 
{
	$("select").hide();
	$("object").hide();
	$("embed").hide();
	if(!$("#window").html()) $("#window").html('<img src="'+root_path+'administrator/images/waiting_animation.gif" width="52" height="52" alt="waiting" class="waiting_animation"/>');
	$("#overlay").show();
	$.ajax({ type: "get", dataType:"html", url: root_path+"administrator/ajax_undo_liste.php", data: "table="+escape(table)+"&id="+id+"&dbfield="+escape(field)+"&form="+escape(form), 
		success: function(content){
			$("#window").html(content);
		}
	});
	
	$("#window").css( "width", "640px");
	$("#window").css( "height", "400px");
	$("#window").css( "left",(($(window).width()-640)/2)+"px");
	$("#window").css( "top", (($(window).height()-400)/2)+"px");
	$("#window").show();
}

function jsCrop(img, imgdest, imgname, id, w, h, tw, th, form, table, field, format)
{
	
	$("select").hide();
	$("object").hide();
	$("embed").hide();
	
	if(!$("#window").html()) $("#window").html('<img src="'+root_path+'administrator/images/waiting_animation.gif" width="52" height="52" alt="waiting" class="waiting_animation"/>');
	$("#overlay").show();
	
	ft = Math.max(Math.max(tw/(980-w), th/(450-h)), 1);
	
	var html = '<div class="jscrop" style="padding:10px; overflow: hidden;"><h1 style="text-align: center; background: gray;">Cropping tool</h1><div class="original" style="float:left"><h2>original</h2>';
	html += '<img src="'+img+'" id="img_target" style="width:'+(tw/ft)+'px;height:'+(th/ft)+'px"/>';
	html += '</div>';
	html += '<div style="'+(w?'width:'+w+'px;':'')+'float:right"><h2>preview</h2>';
	html += '<div id="preview" style="'+(w?'width:'+w+'px;':'')+(h?'height:'+h+'px;':'')+'overflow:hidden;"><img src="'+imgdest+'" id="img_preview" alt="Preview" />';
	html += '</div></div>';
	html += '<span style="visibility:hidden" id="cx"></span>';
	html += '<span style="visibility:hidden" id="cy"></span>';
	html += '<span style="visibility:hidden" id="cw"></span>';
	html += '<span style="visibility:hidden" id="ch"></span>';
	html += '<div style="z-index:10000; position:absolute; bottom:0; left:10px; width:960px; text-align: center; padding: 10px; background: gray; border-top: 10px solid white;"><input type="button" onclick="$(\'select\').show();$(\'object\').show();$(\'embed\').show();$(\'#overlay\').hide();$(\'#window\').hide();" value="cancel"/> <input type="submit" value="'+config_confirm_crop+'" onclick="if(confirm(config_confirm_cropimg)) confirmCrop(\''+form+'\', \''+table+'\', \''+field+'\', '+id+',\''+imgname+'\', \''+format+'\'); return false;"/></div></div>';
	
	$("#window").html(html);
	
	$("#window #img_target").Jcrop(
		{
        	trueSize: [tw, th],
			onChange: function(c){updatePreview(c)},
        	minSize : Array((w?w:0), (h?h:0)),
			onSelect: function(c){updatePreview(c)},
        	aspectRatio: (w && h ? w/h : 0)
      	},
		function()
		{
        	// Use the API to get the real image size
        	var bounds = this.getBounds();
        	boundx = bounds[0];
        	boundy = bounds[1];
			// Store the API in the jcrop_api variable
        	jcrop_api = this;
			hh = h;
			ww = w;
      	}
	);
	
	$("#window").css( "width", "1000px");
	$("#window").css( "height", "600px");
	$("#window").css( "left",(($(window).width()-990)/2)+"px");
	$("#window").css( "top", (($(window).height()-600)/2)+"px");
	$("#window").show();
	$("#overlay").click(
		function(){
			$("select").show();
			$("object").show();
			$("embed").show();
			$(this).hide();
			$("#window").hide();
		}
	);
}
function confirmCrop(form, table, field, id, imgname, format){
	if(form && table && field && id && imgname && format)
		ssaction( '', form, 'cropimg|'+table+'|'+field+'|'+id+'|'+imgname+'|'+format+'|'+$("#cx").html()+'|'+$("#cy").html()+'|'+$("#cw").html()+'|'+$("#ch").html());	
}
function updatePreview(c)
{
	if (parseInt(c.w) > 0)
	{
		$('#window #img_preview').attr('src', $('#window #img_target').attr('src'));
		
		$('#cx').html(c.x);
		$('#cy').html(c.y);
		$('#cw').html(c.w);
		$('#ch').html(c.h);
		
		if(ww)
		{
			var rx = $('#window #preview').width() / c.w;
	  		$('#window #img_preview').css('width', Math.round(rx * boundx) + 'px');
			$('#window #img_preview').css('margin-left', -Math.round(rx * c.x) + 'px');
			//$('#cw').html($('#window #preview').width());
		}
		else
		{
			var rx = $('#window #img_preview').width() / ($('#window #img_target').width()*ft);
			$('#window #preview').css('width', Math.round(rx * c.w) + 'px');
			$('#window #img_preview').css('margin-top', -Math.round(rx * c.x) + 'px');
			//$('#cw').html(Math.round(rx * c.w));
		}
		if(hh)
		{
			var ry = $('#window #preview').height() / c.h;
			$('#window #img_preview').css('height', Math.round(ry * boundy) + 'px');
			$('#window #img_preview').css('margin-top', -Math.round(ry * c.y) + 'px');
			//$('#ch').html($('#window #preview').height());
		}
		else
		{
			var ry = $('#window #img_preview').height() / ($('#window #img_target').height()*ft);
			$('#window #preview').css('height', Math.round(ry * c.h) + 'px');
			$('#window #img_preview').css('margin-top', -Math.round(ry * c.y) + 'px');
			//$('#ch').html(Math.round(ry * c.h));
		}
	}
};
