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

function SmileTickboxLayout( width , height , urlPrefix , siteaccessPrefix, forceOpenChildIn , name ) {
	this.width = width;
	this.height = height;
	this.urlPrefix = urlPrefix;
	this.forceOpenChildIn = forceOpenChildIn;
	if (siteaccessPrefix == "") 
		this.siteAccessPrefix = "";   
	else
		this.siteAccessPrefix = '/' + siteaccessPrefix ;
	
	this.name = name;
}


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

function SmileThickboxOverlay( parentThickbox ) {
	this.overlayNode = null;
	this.parentThickbox = parentThickbox;
}

SmileThickboxOverlay.prototype.open = function ( callback ) {
	if(! this.overlayNode ) {
		var current_object = this;
		var userAgent = navigator.userAgent.toLowerCase();
		
	    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
	        if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div>");
				$("#TB_overlay").click( function() {current_object.closeParent() } );
	        }
	    } else {//all others
	    	if(document.getElementById("TB_overlay") === null) { 
	    		$("body").append("<div id='TB_overlay'></div>");
	    		$("#TB_overlay").click( function() {current_object.closeParent() } );
	        }
	    }

	    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
	    	$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
		    $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		    $("#TB_overlay").css( {filter: "alpha(opacity=75)"});
		}
		
	    this.overlayNode = $("#TB_overlay");
	    
	    this.overlayNode.fadeIn(200 , function() {
		    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
		    	$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
			} else {
			    $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
			}
	    	
	    	if( callback ) {
				callback();
			}
	    } );
		
	} else {
		if(callback) {
			callback();
		}
	}
}

SmileThickboxOverlay.prototype.closeParent = function () {
	this.parentThickbox.close();
}

SmileThickboxOverlay.prototype.close = function ( callback ) {
	if( this.overlayNode ) {
		var current_object = this;
		this.overlayNode.fadeOut( 200 , function() {
			current_object.overlayNode.remove();
			current_object.overlayNode = null;
			$('#TB_HideSelect').remove();
			if(callback)
				callback();
		});
	}
	else
	{
		if( callback )
			callback();
	}
}


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

function SmileThickboxLoader( ) {
	this.loadingImg = null;
}

SmileThickboxLoader.prototype.open = function ( callback ) {
	$("body").append("<div id='TB_load'><img src='" + this.loadingImg + "' /></div>");
	$('#TB_load').fadeIn(200 , function() { 
		if( callback )
			callback(); 
	});	
}

SmileThickboxLoader.prototype.close = function ( callback ) {
	$("#TB_load").fadeOut( 200 , function() {
		$("#TB_load").remove();
		if( callback )
			callback();
	});
}

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

function SmileThickboxWindow () {
	this.layout = null;
	this.state = 'closed';
}

SmileThickboxWindow.prototype.close = function ( callback ) {	
	if( this.state != 'closed' ) {
		$('#TB_window').fadeOut( 200 , function() {
			$('#TB_window').remove();
			if( callback ) {
				callback();
			}
		})
		
		this.state = 'closed';
	} else {
		if ( callback )
		callback();
	}
		
}

SmileThickboxWindow.prototype.open = function ( callback ) {
	
	
	if(this.state == 'closed') {
		this.state = 'opened';
		
		$('body').append('<div id="TB_window"></div>');
		$('#TB_window').append('<div id="TB_ajaxContent"></div>');
	
		
		this.fixCss();
		
		if( callback )
			callback();
		
	} else {
		var current_object = this;
		
		
		
		$('#TB_window').fadeOut( 200 , function() { 
			current_object.fixCss();
			if( callback )
			{
				callback();
				
			}
		});
	}
}

SmileThickboxWindow.prototype.fixCss = function () {
	
	$('#TB_window').css({ display: "none" , 
		  width: this.layout.width +"px",
		  position: "absolute",
		  overflow: 'hidden'
	   });
	
	$("#TB_window").css({marginLeft: '-' + parseInt( (this.layout.width / 2),10) + 'px'});
	
	//if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		height= parseInt( (this.layout.height),10) ;
		height = height/2;
		if( window.scrollY )
			height = parseInt(window.scrollY) - height;
		else
			height = window.document.documentElement.scrollTop - height;
		
		$("#TB_window").css( { 'marginTop' :   height + 'px' } );
	//}
}

SmileThickboxWindow.prototype.updatePosition = function () {
	
	
	if($("#TB_window")[0]) {
				
		height= parseInt( $("#TB_window")[0].clientHeight) ;
		
		$('#TB_window').css({ width: this.layout.width +"px" , marginLeft: '-' + parseInt( (this.layout.width / 2),10) + 'px'} );
		
		if( window.innerHeight && height < window.innerHeight ) {
			height = height/2;
		} else if( window.innerHeight ) {
			height = window.innerHeight/2;
		} else if ( document.documentElement.offsetHeight && height < document.documentElement.offsetHeight) {
			height = height/2;
		} else if ( document.documentElement.offsetHeight ) {
			height = document.documentElement.offsetHeight/2;
		}
	
		if( window.scrollY )
			height = parseInt(window.scrollY) - height;
		else
			height = window.document.documentElement.scrollTop - height;
		
		$("#TB_window").animate( { 'marginTop' :   height + 'px' } , 200 );
		
		if (typeof document.body.style.maxHeight === "undefined") {
			overlay_height = (document.documentElement.scrollHeight > document.body.offsetHeight ? document.documentElement.scrollHeight : document.body.offsetHeight) + 'px';
			$('#TB_overlay').css( { height : overlay_height } );
		}
	}
}

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


function SmileThickbox() {
	this.overlay = new SmileThickboxOverlay(this);
	this.loader = new SmileThickboxLoader();
	this.window = new SmileThickboxWindow();
}

SmileThickbox.prototype.switchLayout = function (layout) {
	this.window.layout = layout;
}

SmileThickbox.prototype.open = function ( callback ) {
	var current_object = this;
	
	current_object.overlay.open();
	current_object.loader.open();
	
	this.window.open( function () {
		
		callback();
	});
	
}


SmileThickbox.prototype.close = function( callback ) {
	var current_object = this;
	
	this.window.close( function() {
		current_object.overlay.close();
		current_object.loader.close(  function() { 
			if( callback )
				callback(); 
		} );		
	});
}

SmileThickbox.prototype.loadData = function loadData(data , callback ) {	
	var current_object = this;
	
	this.loader.close(function(){
		$('#TB_ajaxContent').html(data);
		thickboxStyleHacks();
		$('#TB_window').fadeIn( 50 , function() {
			if( callback ) {
				current_object.window.updatePosition();
				callback();
			}
		} );
	});
	
	
}


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

function SmileThickboxAjaxManager () {
	this.init();
	this.thickbox = new SmileThickbox();
	this.defaultLayout = null;
	this.layouts = Array();
	this.submitElement = null;
}

SmileThickboxAjaxManager.prototype.setDefaultLayout = function (width , height , urlPrefix , siteaccessPrefix , forceOpenChildIn) {
	this.defaultLayout = new SmileTickboxLayout( width , height , urlPrefix , siteaccessPrefix , forceOpenChildIn , 'default');
	this.thickbox.switchLayout(this.defaultLayout);
}

SmileThickboxAjaxManager.prototype.appendLayout = function ( layoutName , width , height , urlPrefix , siteaccessPrefix ,forceOpenChildIn) {
	this.layouts[layoutName] = new SmileTickboxLayout( width , height , urlPrefix , siteaccessPrefix , forceOpenChildIn , layoutName);
}


SmileThickboxAjaxManager.prototype.init = function() {
	var currentManager = this;
	
	$('document').ready(function (){ 
		
		$('form[rel^=ajaxManager] input[type=submit]').click( function() { 
			currentManager.submitElement = this;
			return true;
		} );
		
		$('form[rel^=ajaxManager] input[type=image]').click( function() { 
			currentManager.submitElement = this;
			return true;
		} );
		
		
		$('a[rel^=ajaxManager]').click( function() {
			return currentManager.onLinkClick(this);
		} );
		
		$('form[rel^=ajaxManager]').submit(function() {
			return currentManager.onFormSubmit(this);
		} );
		
	});
}

SmileThickboxAjaxManager.prototype.onLinkClick = function ( linkNode ) {
	
	
	if( linkNode.attributes ) {
		var rel_attr = linkNode.attributes['rel'];
		var pattern_rel = new RegExp("^ajaxManager");
		
		/* Hack for close button */
		if( $(linkNode).hasClass('close') ) {
			return true;
		}
		
		/* Hack for jForms select box */
		if( $(linkNode).hasClass('selectButton') ) {
			return true;
		}
		
		/* Hack for link to a site */
		if( $(linkNode).hasClass('out_site_link') ) {
			return true;
		}
		
		if( (rel_attr && rel_attr.value.match(pattern_rel) ) || this.thickbox.window.layout.forceOpenChildIn) { 
					
			var currentManager = this;
			
			this.retrieveLayout(linkNode);
			var url = this.updateUrl( linkNode.attributes['href'].value , true );
			url = this.updateUrl( url );
			
			this.thickbox.open( function() { 
				currentManager.makeRequest(url, 'GET' , '' );
			});
			
			return false;
			
		} else {
			
			var url = this.updateUrl( linkNode.attributes['href'].value ,true );
			linkNode.href = url; 
		}
	} 
	
	return true;	
}

SmileThickboxAjaxManager.prototype.onFormSubmit = function ( formNode ) {
	
	if( formNode.attributes ) {
		var rel_attr = formNode.attributes['rel'];
		var pattern_rel = new RegExp("^ajaxManager");
		
		if( (rel_attr && rel_attr.value.match(pattern_rel) ) || this.thickbox.window.layout.forceOpenChildIn) {  
			
			var currentManager = this;
			
			this.retrieveLayout(formNode);
			
			var url = this.updateUrl( formNode.attributes['action'].value );
						
			var formMethod = formNode.method;
			
			var formParams = $(formNode.elements).serialize();
				
			if(formParams != "")
				formParams = formParams + "&";
			
			if( this.submitElement != null )
				formParams = formParams + this.submitElement.name + "=" + this.submitElement.value;
			
			this.thickbox.open( function() {
				currentManager.makeRequest(url, formMethod, formParams);
			});
			return false;
			
		} else {
			var url = this.updateUrl( formNode.attributes['action'].value ,true );
			formNode.attributes['action'].value = url;
			return true;
		}
	} 
}


SmileThickboxAjaxManager.prototype.makeRequest = function ( url , method , params) {

	var currentManager = this;
	
	$.ajax( {
		type: method,
		url: url,
		data: params,
		complete: function( XMLHttpRequest , textStatus ) {
			if( XMLHttpRequest.getResponseHeader("Content-Type").match(new RegExp('^text/html') ) ){
		    	currentManager.thickbox.loadData( XMLHttpRequest.responseText, function () {
		    		currentManager.updateCallbacks();
		    	} );
			}
		}
	} );
	
}

SmileThickboxAjaxManager.prototype.updateUrl = function ( url , remove_layout ) {
	var url_pattern = new RegExp('^http://[^/]*');
	//alert(url);
	if (navigator.appName == 'Microsoft Internet Explorer') {
		url = url.replace( url_pattern , '' );
	}
	//alert(url);

	var siteaccessPrefix = this.defaultLayout.siteAccessPrefix;

	if( remove_layout ) {
		var urlPrefix = this.defaultLayout.siteAccessPrefix + '/layout/set/[^/]*';
		url = url.replace( new RegExp("^" + urlPrefix) , this.defaultLayout.siteAccessPrefix );
	}
	else 
	{
		var urlPrefix = this.defaultLayout.siteAccessPrefix + this.thickbox.window.layout.urlPrefix;
		
		if( !url.match( new RegExp("^" + urlPrefix) ) ) {
			/*Remplacement
				if( this.defaultLayout.siteAccessPrefix != "" )
				par
				if( this.defaultLayout.siteAccessPrefix == "" )
				et cela passe.
			*/
			if( this.defaultLayout.siteAccessPrefix == "" ) {
				url = url.replace( new RegExp("^" + this.defaultLayout.siteAccessPrefix) , urlPrefix )
			}
		}
	}
	return url;
}

SmileThickboxAjaxManager.prototype.closeThickbox = function ( ) {
	this.thickbox.close();
	return false;
}

SmileThickboxAjaxManager.prototype.retrieveLayout = function ( node ) {
	
	
	if(node.attributes && node.attributes['rel']) {
		var layout = this.defaultLayout;
		
		var relVal = node.attributes['rel'].value;
		
		var pattern = new RegExp("ajaxManager_(.*)");
		var m = pattern.exec(relVal);
		
		
		if( m != null ) {
			if( this.layouts[m[1]])
				layout = this.layouts[m[1]];
		}
		this.thickbox.switchLayout(layout);
	}
	
}

SmileThickboxAjaxManager.prototype.updateCallbacks = function () {
	
	var currentManager = this;
	
	$('#TB_window a').click( function() { return currentManager.onLinkClick( this ) } );
	
	$('#TB_window form').submit( function() { return currentManager.onFormSubmit( this ) } );
	
	$('#TB_window form input[type=submit]').click( function() { 
		currentManager.submitElement = this;
		return true;
	} );
	
	$('#TB_window form input[type=image]').click( function() { 
		currentManager.submitElement = this;
		return true;
	} );
	
	onThickboxLoad();
	
	onThickboxLoad = function() {};
}


SmileThickboxAjaxManager.prototype.updatePosition = function () {
	this.thickbox.window.updatePosition();
}


function thickboxStyleHacks() {
	
}
