// Modifié par GF, 2008-05-21
var pwisIE4 = (typeof(document.all) != 'undefined' && parseInt(navigator.appVersion) >= 4 && typeof(window.opera) == 'undefined')? 1 : 0;
var isIE = (navigator.appName.substring(0,9)=='Microsoft')? true : false;
var JScSite = null;

var pw_get; 
function pwGET(name)
{
	if(pw_get==undefined)
	{
		pw_get={};
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++)
		{
			var pair = vars[i].split("=");
			pw_get[pair[0]] = unescape(pair[1]); 
		}
	}
	if(!empty(pw_get[name])) return pw_get[name];
	else return '';
} 

function pwSetVisibility(obj,visible)
{
	el=document.getElementById(obj);
	if(el){
		if(visible) el.style.visibility='inherit';
		else el.style.visibility='hidden';
	}
}

function pwShowObject(obj,disp,is_noadjust,is_scroll)
{
	if( $jQ )
	{
		if( typeof obj == 'object' ){
			el = $jQ(obj);
		} else{
			el = $jQ('#'+obj);
		}	
		if( el.length )
		{
			el.show();
	        if(!is_noadjust) pwAdjustIFrame();
	        if(is_scroll) el.scrollIntoView();			
		}
	}
	else
	{
		if( typeof obj == 'object' ){
			el = obj;
		} else{
			el=document.getElementById(obj);
		}
	
		if( el )
		{
			if(!disp)disp='block';
	        if(navigator.appName.indexOf("Microsoft") == -1){
	            switch(el.tagName.toUpperCase())
	            {
	                case 'TR':
	                    disp = 'table-row';
	                break;
	                case 'TD':
	                    disp = 'table-cell';
	                break;
	            }
	        }
	        el.style.display=disp;
	        if(!is_noadjust) pwAdjustIFrame();
	        if(is_scroll) el.scrollIntoView();
		}
	}
}
function pwHideObject(obj, is_noadjust)
{
	if( $jQ )
	{
		if( typeof obj == 'object' ){
			el = $jQ(obj);
		} else{
			el = $jQ('#'+obj);
		}	
		if( el.length )
		{
			el.hide();
	        if( !is_noadjust ) pwAdjustIFrame();			
		}
	}
	else
	{
		if( typeof obj == 'object' ){
			el = obj;
		} else {
			el=document.getElementById(obj);
		}
		if( el )
		{
			el.style.display = 'none';
			if( !is_noadjust ) pwAdjustIFrame();
		}
	}
}

function pwShowOne(show,list,disp,is_noadjust,is_scroll)
{
    if( show == '' || show == 0 || show == '0' )
    {
        show = 'default';
    }
    if( typeof list == 'object' )
    {
        for( var i in list)
        {
            if(i!=show) pwHideObject(list[i], true);
        }
    }

	if( list[show] ) pwShowObject(list[show],disp,true,is_scroll);
	else pwShowObject(show,disp,true,is_scroll);
	if( !is_noadjust ) pwAdjustIFrame();
}

function pwHideOne(show,list,disp,is_noadjust,is_scroll)
{
    if( show == '' || show == 0 || show == '0' )
    {
        show = 'default';
    }
    if( typeof list == 'object' )
    {
        for( var i in list)
        {
            if(i!=show)
            {
            	pwShowObject(list[i],disp,true,is_scroll);
            }
            else
            {
				pwHideObject(list[i],true);
            }
        }
    }
}

function pwToggleDisplay(obj,is_noadjust,is_scroll)
{
	var el = document.getElementById(obj);
	if( el )
	{
		if(el.style.display == 'none') {
			pwShowObject(obj,'',is_noadjust,is_scroll);
		} else {
			pwHideObject(obj,is_noadjust);
		}
	}
}

function pwToggleVisible(obj)
{
	var el = document.getElementById(obj);
	if( typeof el != 'undefined' )
	{
		if(el.style.visibility == 'hidden') {
			el.style.visibility = 'visible';
		} else {
			el.style.visibility = 'hidden';
		}
	}
}

function pwDisplayOnCheck(chk,targetid,display,is_noadjust,is_scroll)
{
if( chk.checked ){
	pwShowObject(targetid,display,is_noadjust,is_scroll);
}else{
	pwHideObject(targetid,is_noadjust);
}
}

function pwHideOnCheck(chk,targetid,display,is_noadjust,is_scroll)
{
if( chk.checked ){
	pwHideObject(targetid,is_noadjust);
}else{
	pwShowObject(targetid,display,is_noadjust,is_scroll);
}
}

function pwCheckAll(frm, cName, check)
{
	var i=0;
	while(frm.elements[i])
	{
		if( frm.elements[i].tagName=='INPUT' && frm.elements[i].type=='checkbox' && frm.elements[i].className.indexOf(cName)!=-1) frm.elements[i].checked = check;
		i++;
	}
}

function pwCheckCount(frm, cName, check)
{
	var nb=0;
	var i=0;
	while(frm.elements[i])
	{
		if( frm.elements[i].tagName=='INPUT' && frm.elements[i].type=='checkbox' && frm.elements[i].className.indexOf(cName)!=-1 && frm.elements[i].checked == check ) nb++;
		i++;
	}
	return nb;
}

function pwGetFirstCheckValue(frm, cName)
{
	var i=0;
	while(frm.elements[i])
	{
		if( frm.elements[i].tagName=='INPUT' && frm.elements[i].type=='checkbox' && frm.elements[i].className.indexOf(cName)!=-1 && frm.elements[i].checked == true ) return frm.elements[i].value;
		i++;
	}
	return false;
}

function pwGetCheckedValue(radioObj)
{
	if(!radioObj) return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked) return radioObj.value;
		else return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function pwSetCheckedValue(radioObj, newValue)
{
	if(!radioObj) return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function pwOpenDetail(filename,targetname,w,h)
{
window.open(filename,targetname,'status=no,location=no,scrollbars=yes,resize=no,directories=no,toolbar=no,menubar=no,copyhistory=yes,width='+w+',height='+h);
return false;
}

function pwOpenWindow(url,targetname,x,y,w,h,is_resize)
{
	var s='';
	if(y!='')s=s+'top='+y+',';
	if(x!='')s=s+'left='+x+',';
	if(w!='')s=s+'width='+w+',';
	if(h!='')s=s+'height='+h+',';
	s=s+'status=no,location=no,scrollbars=yes,resize=';
	if(is_resize==1) s=s+'yes';
	else s=s+'no';
	s=s+',directories=no,toolbar=no,menubar=no,copyhistory=no';
	window.open(url,targetname,s);
}

function pwOpenHelp(url)
{
	pwOpenWindow(url,'_blank',screen.width-450-30,10,450,450,1);
}

function pwChangeLocation(myfield,target)
{
var formindex=myfield.selectedIndex;
if(myfield.value != ""){
target.location=myfield.options[formindex].value;
return true;
}
return (false);
}

function pwFormSubmit(theForm,action)
{
	theForm.action=action;
	theForm.submitform.value=theForm.submitcode.value;
}

function pwAddHTML(idname,html)
{
el = document.getElementById(idname);
if( el ){
	el.innerHTML = el.innerHTML + html;
}
}

function pwSetHTML(idname,html)
{
el = document.getElementById(idname);
if( el ){
	el.innerHTML = html;
}
}

function pwGetHTML(idname,html)
{
el = document.getElementById(idname);
if( el ){
	return el.innerHTML;
}
return '';
}

function pwHtmlSpecialChars(ch)
{
   ch = ch.replace(/&/g,"&amp;");
   ch = ch.replace(/\"/g,"&quot;");
   ch = ch.replace(/\'/g,"&#039;");
   ch = ch.replace(/</g,"&lt;");
   ch = ch.replace(/>/g,"&gt;");
   return ch;
}

var pwgestion_current_height=0;
function pwGestionResizeIFrame(is_first_call)
{
	var myiframe = window.frameElement;
	var is_ok=false;
	if(is_first_call)
	{		
		if(myiframe && myiframe.tagName=='IFRAME' && myiframe.className!='gestion_frame_main' )
		{
			setInterval("pwGestionResizeIFrame()",1000/5);
			is_ok=true;
		}
	}
	else if(myiframe)
	{
		is_ok=true;
	}
	if(is_ok)
	{
		var h=$jQ(document).height();
		var bh=$jQ('#pw_body_height').offset().top+$jQ('#pw_body_height').height();
		//var h=$jQ(body).height();
		if(bh > 0 && h>bh)h=bh;
	    if( !pwIFrame_height ) pwIFrame_height = 250;
	    if( h < pwIFrame_height ) h = pwIFrame_height;
		if( h > 0 )
		{
			if( h != pwgestion_current_height )
			{
				myiframe.height = h;
				pwgestion_current_height = h;
				/*
				if( parent && parent.frameElement && parent.frameElement.tagName=='IFRAME' && parent.frameElement.className!='gestion_frame_main')
				{
					parent.pwGestionResizeIFrame();
				}
				*/				
			}
		}
		//pwDebugEcho($jQ('body').height());
	}
}

var getFFVersion=navigator.userAgent.indexOf("Firefox");
var pwadjust_current_height=0;
function pwAdjustIFrame(e, is_noparent)
{
	return;
	/*
    var myiframe = null;
	try {
	    myiframe = window.frameElement;
	    if(myiframe && myiframe.tagName=='IFRAME' && myiframe.className!='gestion_frame_main')
	    {	    
	    	if( !window.opera )
	    	{
	    		myiframe.style.display="block";	    				    
			    var h=0;
			    e=document.getElementById('pw_body_height');
			    if(e) h=e.offsetTop+15;
				else
				{
					if(myiframe.contentDocument && myiframe.contentDocument.body.offsetHeight) h= myiframe.contentDocument.body.offsetHeight+16;
					else if(myiframe.Document && myiframe.Document.body.scrollHeight) h= myiframe.Document.body.scrollHeight+5;
				}
				//if(myiframe.contentDocument && myiframe.contentDocument.body.scrollWidth > myiframe.contentDocument.body.offsetWidth) h+= 16;
				//else if(myiframe.Document && document.body.scrollWidth > document.body.offsetWidth) h+= 16;
	            if( !pwIFrame_height ) pwIFrame_height = 250;            
	            if( h < pwIFrame_height ) h = pwIFrame_height;
	            var appv = navigator.appVersion;                        
	            if( h != pwadjust_current_height )
	            {
		            myiframe.height = h;
		            pwadjust_current_height = h;
				    if( !is_noparent && parent && parent.frameElement && parent.frameElement.tagName=='IFRAME')
				    {
					    parent.pwAdjustIFrame();
				    }
				}
			}
	    }
	} catch(er){}
	*/
}

function pwFrameLoad(obj)
{
	var scroll_h=obj.contentWindow.document.body.scrollHeight;
	obj.height=scroll_h;
}

function pwScrollTop()
{
	try {
	myiframe = window.frameElement;
	if(myiframe && !window.opera)
	{
		window.parent.document.body.scrollTop = 0;
		if( parent && parent.frameElement )
		{
			parent.pwScrollTop();
		}
	}
	}
	catch(er){}
}

function pwSetCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function pwGetCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function pwDeleteCookie(name, path, domain)
{
    if (pwGetCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*Modification de l'opacité d'un objet id!='' && value = [0-10]*/
function pwSetOpacity(idname, value)
{
	var el = document.getElementById(idname);
	if( el )
	{
		el.style.opacity = value/10;
		el.style.filter = 'alpha(opacity=' + value*10 + ')';
	}
}

function pwNotesDel(url,lang,div_notes_id)
{
	var lng_confirm;
	if(lang=='fr') lng_confirm="Désirez-vous réellement supprimer cette note ?";
	else lng_confirm="Do you really want to delete this note?";
	if(confirm(lng_confirm))
	{
		jQuery('#'+div_notes_id).load(url);
		/*
		new Ajax(url, {
			method: 'get',
			update: $(div_notes_id)
		}).request();
		*/
	}
}



// EDL
/*
retourne l'objet HTML dans lequel se trouve le nom de folder 'pName'
   pName passé en parametre sous forme de string
*/
function pwGetFolderObjFromName (pName) {
	var ret = jQuery('td.fbar');
	for (var i=0; i < ret.length; i++) {
		//if (ret[i].getProperty('folder') == pName) {
		if ($(ret[i]).getProperty('folder') == pName) {
			return (ret[i]);
		}
	}
	return (null);
}

/*
Affiche des div en rapport avec le button passer en parametre
   Boutton passé en parametre doit avoir les atttributs :
   - 'bar'
   - 'folder'
   - 'class_normal'
   - 'class_current'
*/
function pwDisplayFolder(button)
{
    $$('td.'+$(button).getProperty('bar')).each(function(b)
    {
        if( $(b).getProperty('folder') != $(button).getProperty('folder') )
        {
            $(b).removeClass($(b).getProperty('class_current'));
            $(b).addClass($(b).getProperty('class_normal'));
        }
        else
        {
            $(b).removeClass($(button).getProperty('class_normal'));
            $(b).addClass($(button).getProperty('class_current'));
        }
    });


    $$('div.'+$(button).getProperty('bar')).each(function(f)
    {
        if( !f.hasClass($(button).getProperty('folder')) )
        {
            $(f).setStyle('display', 'none');
        }
    });
    $$('div.'+$(button).getProperty('bar')).each(function(f)
    {
        if( f.hasClass($(button).getProperty('folder')) )
        {
            $(f).setStyle('display', 'block');
            $ES('iframe',f).each(function(f1)
		    {
				try{
				f1.contentWindow.pwAdjustIFrame(0, true);
				} catch(er){}
		    });
        }
    });

    pwAdjustIFrame();
	/*
    $$('iframe').each(function(f)
    {
		try{
		f.contentWindow.pwAdjustIFrame();
		} catch(er){}
    });
    */
}

/**
    Ajoute un contenu à un folder.
*/
function pwWrapFolder(name, folder, JSvar)
{
    var out = "";

    out+= "<div class='"+name+" "+folder+"'"

    var current_folder = '';
    var folderElement = $$('div.'+name);
    for( var i=0;i<folderElement.length;i++)
    {
        if( $(folderElement[i]).getStyle('display') == 'block' && $(folderElement[i]).hasClass(folder) )
        {
            current_folder = folder;
            break;
        }
    }

    if( current_folder == folder )
    {
        out+= " style='display:block;'";
    }
    else
    {
        out+= " style='display:none;'";
    }
    out+= ">"+JSvar+"</div>";

    return out;

}

function pwAddLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function LTrim(value)
{
    if( value ) return value.replace(/^\s*/g,'');
    else return '';
}
function RTrim(value)
{
	if( value ) return value.replace(/\s*$/g,'');
	else return '';
}
function Trim(value)
{	
	var val = '';
	if( value )
	{	
    	val = LTrim(value); //value.replace(/^\s*|\s*$/g,'')
    	val = RTrim(val);
	}
    return val;
}

function pwPreparePrint(cls, tag, cnt, is_adjust, footer)
{
    if( typeof $ == 'function' && cls )
    {
        var page_height=800;
        var page_width=700;

        var selector = "";

        // Id du cnt.
        if( $chk(cnt) == false )
        {
            cnt = $(document.body);
        }
        if( $type(cnt) == 'string' )
        {
            selector+= '#'+cnt;

            cnt = $(cnt);
        }
        else if( $type(cnt) == 'object' && $(cnt).getProperty('id') != '' )
        {
            selector+= '#'+$(cnt).getProperty('id');
        }

        if( selector != '' )
        {
            selector+= ' ';
        }
        selector+= tag;

        if( cls != null )
        {
            selector+= '.'+cls;
        }
        // Page 8.5x11@72dpi width = 612 x height = 792
        if( $chk(is_adjust) != false && $chk(cnt) )
        {
            $(cnt).setStyle('width', 700);
        }

        var page_height = 800;
        var original_height = null;
        var total_height = null;
        var breakers = new Array();
        var total_page = 1;
        $$(selector).each(function(breaker)
        {
            if( total_height == null )
            {
                total_height = 0;
                original_height = 0;
            }
            total_height+= ($(breaker).getCoordinates().top-(total_height+original_height))+$(breaker).getCoordinates().height;
            if( total_height >= page_height )
            {
                breaker.setStyle('page-break-before', 'always');
                //breaker.setStyle('background-color', 'brown');
                total_height = 0;
                original_height = $(breaker).getCoordinates().top;
                total_page++;
                breakers.push(breaker);
            }
        });

        if( $chk(footer) && breakers.length > 0 )
        {
            var nb = 1;
            footer = footer.replace('#total_pg#', total_page);
            breakers.each(function(breaker)
            {
                var eDiv = new Element('div');
                $(eDiv).setStyles(
                {
                    'position': 'absolute',
                    'text-align': 'right',
                    'border': '1px red solid',
                    'width': page_width,
                    'left': 0,
                    'top':(page_height*nb)
                });
                $(eDiv).innerHTML = footer.replace('#pg#', nb);
                $(eDiv).inject(document.body);
                $(eDiv).setStyle('top', (page_height*nb)-eDiv.getCoordinates().height);
                nb++;
            });

            var eDiv = new Element('div');
            $(eDiv).setStyles(
            {
                'position': 'absolute',
                'text-align': 'right',
                'border': '1px red solid',
                'width': page_width,
                'left': 0,
                'top':(page_height*nb)
            });
            $(eDiv).innerHTML = footer.replace('#pg#', nb);
            $(eDiv).inject(document.body);
            $(eDiv).setStyle('top', (page_height*nb)-eDiv.getCoordinates().height);
            nb++;
        }
    }

    return false;
}

function pwLoadFrameUrl(frame_name, url, frame_set)
{
	if( frame_name ) {
		var frames = window.top.frames;
		if( frame_set ) {
			var frames = frame_set;
		}
		if( frames && frames.length > 0 ){
			for( var i=0;i<frames.length;i++) {
				if( frames[i].name == frame_name ){
					if( url == '' ){
						url = frames[i].location;
					}
					frames[i].location = url;
				} else if( frames[i].frames.length > 0 ) {
					pwLoadFrameUrl(frame_name, url, frames[i].frames);
				}
			}
		}
	}
}

var pwFrames = new Array();
function pwGetFrame(frame_name, frame_set)
{
	if( frame_name ) {
		if( typeof frame_set == 'undefined' ) {
			var myFrames = window.top.frames;
			pwFrames = new Array();
		} else {
			var myFrames = frame_set;
		}
		
		if( myFrames && myFrames.length > 0 ){
			// Trouve tout les frames de la page.
			for( var i=0;i<myFrames.length;i++) {
				pwFrames.push(myFrames[i]);

				if( myFrames[i].frames.length > 0 ) {
					pwGetFrame(frame_name, myFrames[i].frames);
				}
			}
		}
		
		if( typeof frame_set == 'undefined' ){
			for( var i=0;i < pwFrames.length;i++) {
				if( pwFrames[i].name == frame_name || pwFrames.id == frame_name ){
					return pwFrames[i]; 
				}
			}
		}
	}
}

function pwReloadFrame(frame_name)
{	
	if( frame_name != '' ){
		for( var i=0;i<window.top.frames.length;i++) {
			if( window.top.frames[i].frames )
				for( var j=0;j<window.top.frames[i].frames.length;j++) {
					if( window.top.frames[i].frames[j].name == frame_name )
						window.top.frames[i].frames[j].location=window.top.frames[i].frames[j].location;
				}
		}
	}
}

if( typeof $ == 'function' )
{
    /*
    Script: ajax.cnet.js
    This is an extension to the Ajax class in the <http://mootools.net> library.

    Dependancies:
         mootools - <Moo.js>, <Utility.js>, <String.js>, <Array.js>, <Function.js>, <Element.js>, <XHR.js>
         cnet libraries - <dbug.js>

    Author:
        Aaron Newton, <aaron [dot] newton [at] cnet [dot] com>

    Class: ajax (deprecated)
    This is a legacy namespace (not to be confused with the <Ajax> class) that automatically fires a request when it is created.

        See Also: <Ajax>, <XHR>
    */
    var ajax = new Class({
        initialize: function(url, options) {
            this.ajax = new Ajax(url, options);
            if ($pick(options.fireNow, true))this.ajax.request();
            return this.ajax;
        }
    });

    var CNET_XHR = new Class({
        isSuccess: function(status){
            try {
                if(this.transport.readyState != 4 ||
                     status == "undefined" ||
                    (status < 200 || status >= 300))
                        return false;
                if((!this.transport.responseText.test("COMPONENT_RESPONSE_CODE") ||
                         this.transport.responseText.test("COMPONENT_RESPONSE_CODE=200")) &&
                         !this.transport.responseText.test("<title>Page Not Found") &&
                         !this.transport.responseText.test('errorPageSearchForm')) {
                        return true;
                }
                return false;
            } catch(e) {
                return false;
            }
            return false;
        },
        responseIsSuccess: function(){
            return this.isSuccess(this.status);
        },
        responseIsFailure: function(){
            return !this.responseIsSuccess();
        }
    });
    XHR.implement(new CNET_XHR);
    Ajax.implement(new CNET_XHR);

    var JScSite = new Class(
    {
        initialize : function(name, base_url)
        {
            var ob = this;
            this.name = name;
            this.BASE_URL = base_url;
            this.search = window.location.search;
            var params = new Object();
            this.search.replace('?', '').split('&').each(function(group){
                var args = group.split('=');
                params[args[0]] = args[1];
            });
            this.params = params;

            this.COMP_URL = this.BASE_URL + 'gestion/main/adm.php?ID='+this.params['ID'];
            this.DESIGN_URL = this.BASE_URL + 'design/';
            this.cursor = new Object();

            /*if( window.ie )
            {
                $(document.body).addEvent('mousemove', function(event)
                {
                    ob.cursor = {
                                 'x' : (event.clientX + this.scrollLeft - this.clientLeft)+15,
                                 'y' : (event.clientY + this.scrollTop  - this.clientTop)
                                };
                });
            }
            else
            {
                $(document.body).addEvent('mousemove', function(event)
                {
                    ob.cursor = {
                                 'x' : event.pageX+15,
                                 'y' : event.pageY
                                 };
                });
            }*/

            var url = this.getDesignUrl()+'gestion/icons/ajax-loader.gif';
            new Element('img',
            {
                'id': 'ajax_loader',
                'src': url,
                'styles':
                {
                    'display' : 'none',
                    'position' : 'absolute',
                    'left':0,
                    'top':0
                }
            }).inject(document.body);
        },
        isMooCharged : function() { return true; },
        hasComp : function()
        {
            if( this.search.indexOf('c=') !== false )
            {
                return true;
            }

            return false;
        },
        getBaseUrl : function()
        {
            return this.BASE_URL;
        },
        escapedArgs : function(args)
        {
            var str_args = "";
            for( var i in args )
            {
                if( str_args != '' ) str_args+= "&";
                str_args+= i+"="+escape(args[i]);
            }

            return escape(str_args);
        },
        getCompUrl : function(comp_id, file_id)
        {
            if( file_id )
            {
                file_id = '-'+file_id.slice(file_id.indexOf('-')+1);
            }
            else
            {
                file_id = '';
            }

            return this.COMP_URL+'&c='+comp_id+file_id;
        },
        getSiteUrl : function()
        {
            return this.BASE_URL;
        },
        getDesignUrl : function()
        {
            return this.DESIGN_URL;
        },
        getAjaxUrl : function(options)
        {
            var comp_id = options['comp_id'];
            var file_id = options['file_id'];
            var func_name = options['func_name'];
            var url_args = options['url_args'];
            var ajax_args = options['ajax_args'];

            var url = this.getCompUrl(comp_id, file_id);
            var search = '';
            var params = this.params;
            if( url_args )
            {
                for( var i in url_args )
                {
                    params[i] = url_args[i];
                }
            }
            for( var i in params )
            {
                if( i != 'c' && i != 'ID' )
                {
                    if( search != '' ) search+= '&';
                    search+= i+"="+params[i];
                }
            }
            url+= '&'+search;
            url+= '&ar='+escape(func_name);
            url+= '&aa='+this.escapedArgs(ajax_args);

            return url;
        },
        sendAjax : function(ajax, options)
        {
            if( $type(ajax) == 'object' )
            {
                if( ajax['comp_id'] != '' && ajax['func_name'] != '' )
                {
                    var url = this.getAjaxUrl(ajax);
                    if( url )
                    {
                        if( $type(options) != 'object' )
                        {
                            options = new Object();
                        }

                        if( !options['method'] )
                        {
                            options['method'] = 'get';
                        }
                        this.showLoading();

                        var AjaxRequest = new Ajax(url,options);

                        AjaxRequest.addEvent('onComplete', this.hideLoading);
                        AjaxRequest.addEvent('onComplete', pwAdjustIFrame);

                        AjaxRequest.request();

                        return true;
                    }
                }
            }

            return false;
        },
        postAjax : function()
        {

        },
        showLoading : function()
        {
            $('ajax_loader').setStyles(
            {
                'display' : 'block',
                'position' : 'absolute',
                'visibility' : 'visible'

            });
            $(document.body).addEvent('mousemove', function()
            {
                try{
                    $('ajax_loader').setStyles(
                    {
                        'left' : cSite.cursor.x,
                        'top' : cSite.cursor.y
                    });
                } catch(e){}
            });
        },
        hideLoading : function ()
        {
            $('ajax_loader').setStyles(
            {
                'display' : 'none',
                'position' : 'relative',
                'visibility' : 'hidden'

            });
            $(document.body).removeEvent('mousemove');
        }
    });
}
else
{
    var JScSite = function(name, base_url)
    {
        this.name = name;
        this.BASE_URL = base_url;
        var search = window.location.search;
        var params = new Object();
        var args = search.replace('?', '');

        for( var group in args )
        {
            var arg = group.split('=');
            params[arg[0]] = arg[1];
        }

        this.COMP_URL = this.BASE_URL + 'gestion/main/adm.php?ID='+params['ID'];
        this.DESIGN_URL = this.BASE_URL + 'design/';
        this.cursor = new Object();
    }

    JScSite.prototype.isMooCharged = function() {  return false; };
    JScSite.prototype.hasComp = function() {  return false; };
    JScSite.prototype.getBaseUrl = function()
    {
        return this.BASE_URL;
    };
    JScSite.prototype.escapedArgs = function(args)
    {
        var str_args = "";
        for( var i in args )
        {
            if( str_args != '' ) str_args+= "&";
            str_args+= i+"="+escape(args[i]);
        }
        return str_args;
    };
    JScSite.prototype.getCompUrl = function(comp_id, file_id)
    {
        if( file_id )
        {
            file_id = '-'+file_id.slice(file_id.indexOf('-'));
        }
        else
        {
            file_id = '';
        }

        return this.COMP_URL+'&c='+comp_id+file_id;
    };
    JScSite.prototype.getSiteUrl = function()
    {
        return this.BASE_URL;
    };
    JScSite.prototype.getDesignUrl = function()
    {
        return this.DESIGN_URL;
    };
}

var includeOnce_scripts = new Array();
jQuery.includeOnce = function(script_name, is_custom)
{	
	if( !(script_name in includeOnce_scripts) )
	{		
		includeOnce_scripts[script_name] = 1;
		if(is_custom)
		{
			script_name=site_config['base_url']+"custom/js/"+script_name;
		}
		else if(script_name.substr(0, site_config['base_url'].length) != site_config['base_url'])
		{
			script_name=site_config['base_url']+"js/"+script_name;
		}
		
		//jQuery.getScript(script_name); //, function(js){alert(js);}		
        $jQ.ajax({
	        url: script_name,
        	dataType: "script",async: false,type:'GET',scriptCharset:"iso-8859-1"
        	//, success: function(js){pwDebugEcho(script_name);}
        	//, success: function(js){if(jQuery.browser.safari){eval(js);}}
        });        
	}
};

jQuery.includeOnce('jquery.sizes.js');

jQuery.fn.scrollIntoView = function()
{
	var offset=jQuery(this).offset();
	var ot=offset.top;		
	var wh=jQuery(window).height();
	var wst=jQuery(window).scrollTop();
	if(ot<wst || ot>wst+wh)
	{	
		ot-=50;
		if(ot<0)ot=0;
		jQuery(window).scrollTop(ot);		
		jQuery('html, body').animate({scrollTop:ot});
	}
};


function pwDebugEcho(msg)
{
	if(jQuery('#pw_debug_out').size()==0) jQuery('body').prepend("<div id='pw_debug_out' style='height:100px;overflow:scroll;font-family:sans-serif;font-size:12px;color:#0000DD;background-color:#FFFFFF;z-index:10000;border-bottom:1px dashed #0000DD;padding:2px 5px;border-left:2px solid #0000DD;margin:1px;'></div>");
		
	var out='';
	if( is_object(msg) || is_array(msg) )
	{
		out+= "<pre>"+htmlspecialchars(print_r(msg, true))+"</pre>";
	}
	else if( empty(msg) )
	{
		out+= '&nbsp;';
	}
	else
	{
		out+= nl2br(htmlspecialchars(msg));
	}
	//alert(out);		
	jQuery('#pw_debug_out').prepend("<div>"+out+"</div>");
}

/*
(function($){
$.fn.vanish = function(speed)  
{
	return this.each(function(){
		var $this = $(this);
		$this.clone().insertBefore(this).fadeOut(speed).remove();
	});
};
})(jQuery);
*/

jQuery.extend(
  jQuery.expr[ ":" ], 
  { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

/*
jQuery.get = function() {
     var dimensions = {width: 0, height: 0};
     if (document.documentElement) {
         dimensions.width = document.documentElement.offsetWidth;
         dimensions.height = document.documentElement.offsetHeight;
     } else if (window.innerWidth && window.innerHeight) {
         dimensions.width = window.innerWidth;
         dimensions.height = window.innerHeight;
     }
     return dimensions;
}
*/

function pwSwapImage(a,b,w,h)
{
	jQuery(a).prop('src',b);
	if(w)
	{
		jQuery(a).prop('width',w)
	}
	if(h)
	{
		jQuery(a).prop('height',h)
	}
}

function pwSetFocus(formname, elname)
{
    if( formname != '' && elname != ''  )
    {
    	try{
    	document.forms[formname].elements[elname].focus();
		}catch(e){}
    }
}

function empty(mixed_var)
{
    var key;

    if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }

    return false;
}

function is_array(mixed_var)
{
    var ini,
        _getFuncName = function (fn) {
            var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
            if (!name) {
                return '(Anonymous)';
            }
            return name[1];
        },
        _isArray = function (mixed_var) {
            if (!mixed_var || typeof mixed_var !== 'object' || typeof mixed_var.length !== 'number') {
                return false;
            }
            var len = mixed_var.length;
            mixed_var[mixed_var.length] = 'bogus';
            if (len !== mixed_var.length) { 
                mixed_var.length -= 1;
                return true;
            }
            delete mixed_var[mixed_var.length];
            return false;
        };

    if(!mixed_var || typeof mixed_var !== 'object') {
        return false;
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    
    ini = this.php_js.ini['phpjs.objectsAsArrays'];

    return _isArray(mixed_var) ||
        // Allow returning true unless user has called
        // ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays
        ((!ini || ( // if it's not set to 0 and it's not 'off', check for objects as arrays
        (parseInt(ini.local_value, 10) !== 0 && (!ini.local_value.toLowerCase || ini.local_value.toLowerCase() !== 'off')))
        ) && (
        Object.prototype.toString.call(mixed_var) === '[object Object]' && _getFuncName(mixed_var.constructor) === 'Object' // Most likely a literal and intended as assoc. array
        ));
}

function is_object(mixed_var)
{
    if (Object.prototype.toString.call(mixed_var) === '[object Array]') {
        return false;
    }
    return mixed_var !== null && typeof mixed_var == 'object';
}

function htmlspecialchars (string, quote_style, charset, double_encode)
{
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}

function nl2br(str, is_xhtml)
{
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function print_r (array, return_val) {
    var output = '',
        pad_char = ' ',
        pad_val = 4,
        d = this.window.document,
        getFuncName = function (fn) {
            var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
            if (!name) {
                return '(Anonymous)';
            }
            return name[1];
        },
        repeat_char = function (len, pad_char) {
            var str = '';
            for (var i = 0; i < len; i++) {
                str += pad_char;
            }
            return str;
        },
        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 (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') {
                str += 'Array\n' + base_pad + '(\n';
                for (var key in obj) {
                    if (Object.prototype.toString.call(obj[key]) === '[object 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 if (obj === null || obj === undefined) {
                str = '';
            }
            else { // for our "resource" class
                str = obj.toString();
            }

            return str;
        };

    output = formatArray(array, 0, pad_val, pad_char);

    if (return_val !== true) {
        if (d.body) {
            this.echo(output);
        }
        else {
            try {
                d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
                this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');
            } catch (e) {
                this.echo(output); // Outputting as plain text may work in some plain XML
            }
        }
        return true;
    }
    return output;
}

function echo () {
    var arg = '',
        argc = arguments.length,
        argv = arguments,
        i = 0,
        holder, win = this.window,
        d = win.document,
        ns_xhtml = 'http://www.w3.org/1999/xhtml',
        ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; // If we're in a XUL context
    var stringToDOM = function (str, parent, ns, container) {
        var extraNSs = '';
        if (ns === ns_xul) {
            extraNSs = ' xmlns:html="' + ns_xhtml + '"';
        }
        var stringContainer = '<' + container + ' xmlns="' + ns + '"' + extraNSs + '>' + str + '</' + container + '>';
        var dils = win.DOMImplementationLS,
            dp = win.DOMParser,
            ax = win.ActiveXObject;
        if (dils && dils.createLSInput && dils.createLSParser) {
            // Follows the DOM 3 Load and Save standard, but not
            // implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though
            // possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could
            // attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file)
            var lsInput = dils.createLSInput();
            // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
            lsInput.stringData = stringContainer;
            var lsParser = dils.createLSParser(1, null); // synchronous, no schema type
            return lsParser.parse(lsInput).firstChild;
        } else if (dp) {
            // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
            try {
                var fc = new dp().parseFromString(stringContainer, 'text/xml');
                if (fc && fc.documentElement && fc.documentElement.localName !== 'parsererror' && fc.documentElement.namespaceURI !== 'http://www.mozilla.org/newlayout/xml/parsererror.xml') {
                    return fc.documentElement.firstChild;
                }
                // If there's a parsing error, we just continue on
            } catch (e) {
                // If there's a parsing error, we just continue on
            }
        } else if (ax) { // We don't bother with a holder in Explorer as it doesn't support namespaces
            var axo = new ax('MSXML2.DOMDocument');
            axo.loadXML(str);
            return axo.documentElement;
        }
/*else if (win.XMLHttpRequest) { // Supposed to work in older Safari
            var req = new win.XMLHttpRequest;
            req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(str), false);
            if (req.overrideMimeType) {
                req.overrideMimeType('application/xml');
            }
            req.send(null);
            return req.responseXML;
        }*/
        // Document fragment did not work with innerHTML, so we create a temporary element holder
        // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
        //if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways)
        if (d.createElementNS && // Browser supports the method
        (d.documentElement.namespaceURI || // We can use if the document is using a namespace
        d.documentElement.nodeName.toLowerCase() !== 'html' || // We know it's not HTML4 or less, if the tag is not HTML (even if the root namespace is null)
        (d.contentType && d.contentType !== 'text/html') // We know it's not regular HTML4 or less if this is Mozilla (only browser supporting the attribute) and the content type is something other than text/html; other HTML5 roots (like svg) still have a namespace
        )) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways); last test is for the sake of being in a pure XML document
            holder = d.createElementNS(ns, container);
        } else {
            holder = d.createElement(container); // Document fragment did not work with innerHTML
        }
        holder.innerHTML = str;
        while (holder.firstChild) {
            parent.appendChild(holder.firstChild);
        }
        return false;
        // throw 'Your browser does not support DOM parsing as required by echo()';
    };


    var ieFix = function (node) {
        if (node.nodeType === 1) {
            var newNode = d.createElement(node.nodeName);
            var i, len;
            if (node.attributes && node.attributes.length > 0) {
                for (i = 0, len = node.attributes.length; i < len; i++) {
                    newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
                }
            }
            if (node.childNodes && node.childNodes.length > 0) {
                for (i = 0, len = node.childNodes.length; i < len; i++) {
                    newNode.appendChild(ieFix(node.childNodes[i]));
                }
            }
            return newNode;
        } else {
            return d.createTextNode(node.nodeValue);
        }
    };

    var replacer = function (s, m1, m2) {
        // We assume for now that embedded variables do not have dollar sign; to add a dollar sign, you currently must use {$$var} (We might change this, however.)
        // Doesn't cover all cases yet: see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
        if (m1 !== '\\') {
            return m1 + eval(m2);
        } else {
            return s;
        }
    };

    this.php_js = this.php_js || {};
    var phpjs = this.php_js,
        ini = phpjs.ini,
        obs = phpjs.obs;
    for (i = 0; i < argc; i++) {
        arg = argv[i];
        if (ini && ini['phpjs.echo_embedded_vars']) {
            arg = arg.replace(/(.?)\{?\$(\w*?\}|\w*)/g, replacer);
        }

        if (!phpjs.flushing && obs && obs.length) { // If flushing we output, but otherwise presence of a buffer means caching output
            obs[obs.length - 1].buffer += arg;
            continue;
        }

        if (d.appendChild) {
            if (d.body) {
                if (win.navigator.appName === 'Microsoft Internet Explorer') { // We unfortunately cannot use feature detection, since this is an IE bug with cloneNode nodes being appended
                    d.body.appendChild(stringToDOM(ieFix(arg)));
                } else {
                    var unappendedLeft = stringToDOM(arg, d.body, ns_xhtml, 'div').cloneNode(true); // We will not actually append the div tag (just using for providing XHTML namespace by default)
                    if (unappendedLeft) {
                        d.body.appendChild(unappendedLeft);
                    }
                }
            } else {
                d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description')); // We will not actually append the description tag (just using for providing XUL namespace by default)
            }
        } else if (d.write) {
            d.write(arg);
        }
/* else { // This could recurse if we ever add print!
            print(arg);
        }*/
    }
}
