var dossierTest = "";

var dds = [];
	
var overlays = [];
var nodes = [];

var nPanel = 1;

var panel;


function newPopUp( titleContent, bodyContent, iWidth, iHeight ) 
{
	YUI({combine: true, timeout: 10000}).use('overlay', function(Y) 
	{
		var overlay,
		    n = 0,
		    xy = Y.one("#allPanel").getXY();
	
		function getOverlayXY(xy, i)
		{
	        return [xy[0] + i * 60, xy[1] + i * 40];
	    }
		
		function setPositionMenu(xy, i)
		{
			mX = window.innerWidth - 380;
			mY = 80;
			
			return [mX, mY];
		}
		
	
        ovrXY = getOverlayXY(xy, nPanel);
        ovrZIndex = nPanel+1;
        
        menuXY = setPositionMenu(xy, nPanel);

        // Setup n Overlays, with increasing zIndex values
        
        if ( titleContent === "MENU" )
        {
	        overlay = new Y.Overlay({
	            zIndex:ovrZIndex,
	            xy:menuXY,
	            /*width:"400px",
	            height:"200px",*/
	            headerContent: getPopUp( bodyContent, titleContent, nPanel )
	           /* bodyContent: '<div class="close_panel" id="close_panel'+i+'">&nbsp;</div>' + panelContent*/
	        });
        }
        else
        {
        	overlay = new Y.Overlay({
	            zIndex:ovrZIndex,
	            xy:ovrXY,
	            /*width:"400px",
	            height:"200px",*/
	            headerContent: '<div class="close_panel" id="close_panel'+nPanel+'">&nbsp;</div>' + getPopUp( bodyContent, titleContent, nPanel ) 
	           /* bodyContent: '<div class="close_panel" id="close_panel'+i+'">&nbsp;</div>' + panelContent*/
	        });
        }

        
        overlay.render("#allPanel");
        overlays.push(overlay);

        // Update body whenever zIndex changes
        overlay.after("zIndexChange", function(e) {
            //this.set("bodyContent", "zIndex = " + e.newVal);
        });
        
        
        // TODO Delete popup in overlays !!!
       /* function handleClick(e) {
        	//Pass the event facade to the logger or console for
            //inspection:
        	toMatch = panel.toString();
			patt = /yui[\w]+/gi;
			
			trace(Y);
			
			trace("before");
			trace( overlays );
			trace(" ");
			overlays = removeEntryFromAnArray(overlays, "overlay["+e.target.toString().match(patt)+"]");
			
			trace("after");
			trace( overlays );
        }*/
        
        function removeEntryFromAnArray( a, entry )
        {
        	newArray = [];
        	trace(entry);
        	for ( i = 0; i < a.length; ++i )
        	{
        		if ( a[i] != entry )
        		{ 
        			newArray.push(a[i]);
        		}
        	}
        	
        	return newArray;
        }

        YUI().use('node-base', function(Y) 
        {
        	Y.on("click", Y.bind(overlay.destroy, overlay), "#close_panel"+nPanel+"");
        	//Y.on("click", handleClick, "#close_panel"+nPanel+"");
        });
        
       
        
	    function onStackMouseDown(e) 
	    {
	        var widget = Y.Widget.getByNode(e.target);
	
	        // If user clicked on an Overlay, bring it to the top of the stack
	        if (widget && widget instanceof Y.Overlay) {
	            bringToTop(widget);
	        }
	    }
	
	    // zIndex comparator
	    function byZIndexDesc(a, b) 
	    {
	    	// TODO Fix it
	    	//if (!a || !b || !a.hasImpl(Y.WidgetStack) || !b.hasImpl(Y.WidgetStack)) {
	    	//	return 0;
	    	//} else {
	            var aZ = a.get("zIndex");
	            var bZ = b.get("zIndex");
	        
	            if (aZ > bZ) {
	                return -1;
	            } else if (aZ < bZ) {
	                return 1;
	            } else {
	                return 0;
	            }
	        //}
	    }
	
	    function bringToTop(overlay) 
	    {
	        // Sort overlays by their numerical zIndex values
	        overlays.sort(byZIndexDesc);
	
	        // Get the highest one
	        var highest = overlays[0];
	
	        // If the overlay is not the highest one, switch zIndices
	        if (highest !== overlay) {
	            var highestZ = highest.get("zIndex");
	            var overlayZ = overlay.get("zIndex");
	
	            overlay.set("zIndex", highestZ);
	            highest.set("zIndex", overlayZ);
	        }
	    }
	    
	    toMatch = overlay.toString();
		patt = /[0-9A-Za-z_]+[^overlay\[\]]/gi;
		
	    Y.on("mousedown", onStackMouseDown, "#"+toMatch.match(patt));

		document.getElementById("b"+nPanel).style.width = iWidth+"px";
		document.getElementById("b"+nPanel).style.height = iHeight+"px";
	    
	    nPanel += 1;

	    YUI().use('dd-plugin', function(Y) 
	    {
		    nodes[nPanel] = Y.get('#'+toMatch.match(patt));
		    nodes[nPanel].plug(Y.Plugin.Drag);
		    nodes[nPanel].plug(Y.Plugin.DragConstrained, {
            	constrain2node: '#allPanel'
            });
		    nodes[nPanel].dd.addHandle('#border_left');
		    nodes[nPanel].dd.addHandle('#border_right'); 
		    nodes[nPanel].dd.addHandle('#border_top'); 
		    nodes[nPanel].dd.addHandle('#border_bottom');
		    nodes[nPanel].dd.addHandle('#title_content_body');
	    });
	    
	    if ( titleContent === "MENU" )
        {
	    	setUpMenu();
        }
	});
}

function setPopUp( action, id )
{
	var req = null;
	var doc ;
	//trace("Started...");
	
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		if (req.overrideMimeType) {
			req.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject) 
	{
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {
			}
		}
	}
	
	req.onreadystatechange = function()
	{
		if (req.readyState == 4) 
		{
			if (req.status == 200) 
			{
				doc = req.responseText;
				
				res = doc.split(" | ");

				if ( res[0] == 1 )
				{
					document.getElementById('menu').innerHTML = res[1];
					setUpMenu();
					
					//newPopUp("MENU", res[1]);
				}
				else if ( res[0] == 2 )
				{
					newPopUp( res[1], res[2], res[3], res[4] );
				}
				else if ( res[0] == 3 )
				{
					//document.getElementById('sEmission').innerHTML = res[1];
					
					//setUpArchives();
				}
				else if ( res[0] == 4 )
				{
					newPopUp( res[1], res[2] );
				}
				else if ( res[0] == 5 )
				{
					newPopUp( res[1], res[2], res[3], res[4] );
				}
				else if ( res[0] == 6 )
				{
					newPopUp( "TCHAT", res[1], res[2], res[3]  );
				}
				else if ( res[0] == 7 )
				{
					document.getElementById('blog').innerHTML = res[1];
				}
			}
			else 
			{
				trace("Error: returned status code " + req.status + " " + req.statusText);
			}
		}
	};
	if (location.hostname == "localhost") 
	{
		req.open("POST", "http://localhost/RadioMNE/template.php", true);
	}
	else
	if ( location.hostname == "192.168.0.12" )
	{
		req.open("POST", "http://192.168.0.12/MNE_DEV/template.php", true);
	}
	else
	{
		req.open("POST", "http://"+location.hostname+dossierTest+"/template.php", true);
	}
	
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send("action="+action+"&id="+id);
	
	return(doc);
}


function getPopUp ( popUpContent, titlePopUpContent, id ) 
{
	panelContent = 
	'<div id="border_top">'+
		'<table style="width:100%;height:18px;border-collapse:collapse;padding:0;margin:0;">'+
			'<tr style="padding:0;margin:0;">'+
				'<td style="width:17px;padding:0;margin:0;">'+
					'<div id="content-round-top" style="background-image:url(\'img/round_top-left.png\');background-repeat:no-repeat;">&nbsp;</div>'+
				'</td>'+
				'<td style="padding:0;margin:0;">'+
					'<div id="content-top" style="background-image:url(\'img/border-top.png\'); background-repeat:repeat-x;">&nbsp;</div>'+
				'</td>'+
				'<td style="width:17px;padding:0;margin:0;">'+
					'<div id="content-round-top" style="background-image:url(\'img/round_top-right.png\');background-repeat:no-repeat;">&nbsp;</div>'+
				'</td>'+
			'</tr>'+
		'</table>'+
	'</div>'+

	'<div id="content">'+
		'<div id="border_left"></div>'+
		
		'<div id="content_inside">'+
			'<div id="corner_top_left">&nbsp;</div>'+
			'<div id="corner_top_right">&nbsp;</div>'+
			'<div id="title_content_body">'+
				titlePopUpContent +
			'</div>'+
			'<div class="content-body" id="b'+id+'">'+
				popUpContent +
			'</div>'+
			
			'<div id="corner_bottom_left">&nbsp;</div>'+
			'<div id="corner_bottom_right">&nbsp;</div>'+
		'</div>'+
		
		'<div id="border_right"></div>'+
	'</div>'+

	'<div id="border_bottom">'+
		'<table style="width:100%;height:16px;border-collapse:collapse;padding:0;margin:0;">'+
			'<tr style="padding:0;margin:0;">'+
				'<td style="width:17px;padding:0;margin:0;">'+
					'<div id="content-round-top" style="background-image:url(\'img/round_bottom-left.png\');background-repeat:no-repeat;">&nbsp;</div>'+
				'</td>'+
				'<td style="padding:0;margin:0;">'+
					'<div id="content-top" style="background-image:url(\'img/border-top.png\'); background-repeat:repeat-x;">&nbsp;</div>'+
				'</td>'+
				'<td style="width:17px;padding:0;margin:0;">'+
					'<div id="content-round-top" style="background-image:url(\'img/round_bottom-right.png\');background-repeat:no-repeat;">&nbsp;</div>'+
				'</td>'+
			'</tr>'+
		'</table>'+
	'</div>';
	
	return panelContent;
}

//----- START SHOW/HIDE
var showhide = new Object();

var sliding = new Object();

var temp = 0.0; // 0.03


// Class ShowHide markup
function initShowHidePost(id, action)
{	
	if ( !showhide[id] )
	{
		showhide[id] = new ShowHidePost(id);
	}
	showhide[id].initHidePost();	
}
function ShowHidePost(id) 
{
	var Obj = this;

	var postId;
	
	this.idPost = id;

	this.pattern=/[0-9.]+/gi;

    this.initHidePost = function()
    {
    	this.postId = document.getElementById(this.idPost);
    	
    	sliding[this.idPost] = 1;
    	
    	if ( sliding[this.idPost + "heightId"] == null )
		{ 
			heightId = document.defaultView.getComputedStyle(this.postId, null).height;
			
			sliding[this.idPost + "heightId"] = heightId.match(this.pattern); 
		}
		
    	document.getElementById(this.idPost).style.height = 0;
    }
	
	
    this.doShowHidePost = function()
    {
    	this.postId = document.getElementById(this.idPost);
    	
    	clearTimeout(sliding[this.idPost + "timeout"]);

    	if ( sliding[this.idPost] == null || sliding[this.idPost] == 0)
    	{
    		sliding[this.idPost] = 1;
    		
    		if ( sliding[this.idPost + "heightId"] == null )
    		{ 
    			heightId = document.defaultView.getComputedStyle(this.postId, null).height;
    		
    			sliding[this.idPost + "heightId"] = heightId.match(this.pattern); 
    		}
    	
    		this.hidePost();
    	}
    	else
    	{
    		sliding[this.idPost] = 0;
    		this.showPost();
    	}
    }
    
    this.h = 0;

    this.hidePost = function()
    {
    	sheight = document.defaultView.getComputedStyle(this.postId, null).height;
    	
    	pourcent = (sheight.match(this.pattern) * 15) / 100;
    	
    	sheight = Math.abs(sheight.match(this.pattern)) - Math.abs(pourcent);
    	
    	this.h = this.h - 50;
    	
    	document.getElementById(this.idPost).style.height = this.h + "%";
    	
    	if (this.h < 1) 
    	{
    		//this.h = 0;
    		document.getElementById(this.idPost).style.height = 0;
    		clearTimeout(sliding[this.idPost + "timeout"]);
    	}
    	else
    	{
    		sliding[this.idPost + "timeout"] = setTimeout(function() { Obj.hidePost(this.idPost); }, temp);
    	}
    };
  
    this.showPost = function()
    {
    	sheight = document.defaultView.getComputedStyle(this.postId, null).height;
   
    	pourcent = (sliding[this.idPost + "heightId"] * 5) / 100;
    	
    	
    	
    	this.h = this.h + 50;
    	
    	document.getElementById(this.idPost).style.height = this.h + "%";

    	
    	if ( this.h >= 100 ) 
    	//if (sheight >= sliding[this.idPost + "heightId"]) 
    	{
    		//this.h = 0;
    		clearTimeout(sliding[this.idPost + "timeout"]);
    	}
    	else
    	{
    		sliding[this.idPost + "timeout"] = setTimeout(function() { Obj.showPost(this.idPost); }, temp); // in milliseconds
    	}
    };
    
    /*
	this.hidePost = function()
    {
    	sheight = document.defaultView.getComputedStyle(this.postId, null).height;
    	
    	pourcent = (sheight.match(this.pattern) * 15) / 100;
    	
    	sheight = Math.abs(sheight.match(this.pattern)) - Math.abs(pourcent);
    	
    	document.getElementById(this.idPost).style.height = sheight + "px";

    	if (sheight < 1) 
    	{
    		document.getElementById(this.idPost).style.height = 0;
    		clearTimeout(sliding[this.idPost + "timeout"]);
    	}
    	else
    	{
    		sliding[this.idPost + "timeout"] = setTimeout(function() { Obj.hidePost(this.idPost); }, temp);
    	}
    };

    this.showPost = function()
    {
    	sheight = document.defaultView.getComputedStyle(this.postId, null).height;
   
    	pourcent = (sliding[this.idPost + "heightId"] * 5) / 100;

    	sheight = Math.abs(sheight.match(this.pattern)) + Math.abs(pourcent);
    	
    	document.getElementById(this.idPost).style.height = sheight + "px";
    	
    	//if ( sheight >= 100 ) 
    	if (sheight >= sliding[this.idPost + "heightId"]) 
    	{
    		clearTimeout(sliding[this.idPost + "timeout"]);
    	}
    	else
    	{
    		sliding[this.idPost + "timeout"] = setTimeout(function() { Obj.showPost(this.idPost); }, temp); // in milliseconds
    	}
    };
    */
}




// ----- RECHERCHE 
function registerNewsLetter( e, value )
{
	if ( e.type == "keypress" )
	{
		var keynum;
		if(window.event) // IE
		{
			keynum = e.keyCode;
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
			keynum = e.which;
		}
		
		if (keynum == 13 ) { window.location.replace("http://"+window.location.hostname+"news/"+value); }
	}
	else
	{
		window.location.replace("http://"+window.location.hostname+"news/"+value);
	}
}




function search( e, value )
{
	if ( e.type == "keypress" )
	{
		var keynum;
		if(window.event) // IE
		{
			keynum = e.keyCode;
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
			keynum = e.which;
		}

		if (keynum == 13 ) { window.location.replace( "http://"+window.location.hostname+"/search/"+value ); }
	}
	else
	{
		
		window.location.replace( "http://"+window.location.hostname+"/search/"+value );
	}
}


/*function search( search )
{
	var req = null;
	var doc ;

	if (window.XMLHttpRequest) 
	{
		req = new XMLHttpRequest();
		if (req.overrideMimeType) 
		{
			req.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject) 
	{
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {
			}
		}
	}
	
	req.onreadystatechange = function()
	{
		//trace("Wait server...");
		if (req.readyState == 4) 
		{
			if (req.status == 200) 
			{
				str = req.responseText;
				trace(str);
			}
			else 
			{
				trace("Error: returned status code " + req.status + " " + req.statusText);
			}
		}
	};
	
	if (location.hostname == "localhost") 
	{
		req.open("POST", "http://localhost/MNE_Dev/search.php", true);
	}
	else
	if ( location.hostname == "192.168.0.12" )
	{
		req.open("POST", "http://192.168.0.12/MNE_DEV/search.php", true);
	}
	else
	{
		req.open("POST", "http://"+location.hostname+dossierTest+"/search.php", true);
	}
	
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send("search="+search);
	
	return(doc);
}
*/



function clear()
{
	sliding = new Object();
}




// ----- END SHOW/HIDE

function clearLog()
{
	document.getElementById( 'message' ).innerHTML = "";
}

function trace( message )
{
	document.getElementById( 'message' ).innerHTML += "<span>" + message + "</span><br />";
}
