/**************************************************************************
**************************************************************************
					ACTION LIST
**************************************************************************
**************************************************************************/

// ******************************************************** BOXY VAR

var boxyAlert = false;
var boxyFriendAdd = false;
var boxyMenuAddFriend = false;
var boxyMenuModifyFriend = false;
var boxyRestoShareFriend = false;
var boxyRestoShareResto = false;

// ******************************************************** BOXY VAR

$(document).ready(function() {


// ******************************************************** SCROLL IN PAGE
	
	$('#linkRegister').click(function(e){
		e.preventDefault();
		//$.scrollTo( $('form #register'), 800 );
		//$.scrollTo( '500px', 800 );
		$.scrollTo( {top:'660px'}, 800 );
		$('#registerFormUpdate').html("Merci de vous enregistrer en remplissant tous les champs de ce formulaire.").animate({opacity: opacityVariables('show')}, 500).css('borderWidth',1).animate({'borderWidth':1}, 3000).animate({opacity: opacityVariables('hide')}, 500);
		
	});

// ******************************************************** SCROLL IN PAGE 

// ******************************************************** REGISTER USER

$('#registerButton').click(function(){
	//e.preventDefault();
	var totalErrors = 0;
	// VERIFY IF ALL FIELDS ARE FILLED
	$('#register input').each(function() {
		var inputValue = $(this).val();
		if(inputValue == '' || inputValue == 'Prénom' || inputValue == 'Nom' || inputValue == 'Email' || inputValue == 'Mot de passe' || inputValue == 'Ville' || inputValue == 'Code postal' || inputValue == 'Année de naissance') { 
			totalErrors++; 
			$(this).css('opacity','hide').css('background-image','url(images/FormInputBGRed.png)').css('color','#660014').animate({'opacity':'show'}, 500);
		}
	});
	
	// SHOW ALERT WHEN MISSING FIELD ELSE SERIALIZE VARIABLES AND SEND
	if(totalErrors > 0) { 
		$('#registerFormUpdate').html("Tous les champs sont obligatoire.").animate({opacity: opacityVariables('show')}, 500).css('borderWidth',1).animate({'borderWidth':1}, 3000).animate({opacity: opacityVariables('hide')}, 500);
	} else {
		registerUser();
	}
	
});

var registerUser = function(){
	$('#registerFormUpdate').html("Enregistrement en-cour...").fadeTo("slow", 1);
		var registerVariables = $('#register').serialize();
		var registerUrl = 'Register';
			$.ajax({
				type: "POST",
				url: registerUrl,
				data: registerVariables,
				success: function(msg){
					if(msg != 'success') {
					$('#registerFormUpdate').html(msg).animate({opacity: opacityVariables('show')}, 500).css('borderWidth',1).animate({'borderWidth':1}, 7000).animate({opacity: opacityVariables('hide')}, 500);
					} else {
					$('#registerFormUpdate').animate({opacity: opacityVariables('hide')}, 500);
					$('#message').html('Un email (à '+$('input[name="email"]').val()+') vous a été envoyé.  Pour activer votre compte Delici.eu, vous devez cliquez sur le lien dans cet email.  Merci.');
					alertValidationBtn('#message', 'Ok');
					new Boxy('#message', {modal: true});
					
					}
				}
			});
}

// ******************************************************** REGISTER USER

// ******************************************************** PASSWORD LOST

var passwordLost = function(){
	
	
	var passwordVariables = $('#forgotPassword').serialize();
	var loginUrl = 'forgotPassword';
			$.ajax({
				type: "POST",
				url: loginUrl,
				data: passwordVariables,
				success: function(msg){
					
						$('#message').html(msg);
						alertValidationBtn('#message', 'Ok');
						new Boxy('#message', {modal: true});
				}//, error: function(xmlhttp) { alert("An error - xmlhttp.readyState: " + xmlhttp.readyState + "\nAn error - xmlhttp.status: " + xmlhttp.status); }
			});

}

$('#passwordButton').click(function(){
		if($('input[name="emailPassword"]').val() != 'Email') { passwordLost(); } else {
			$('#message').html('Un email doit être renseigné.');
			alertValidationBtn('#message', 'Ok');
			new Boxy('#message', {modal: true});
		}
	});

// ******************************************************** PASSWORD LOST


}); // END $(document).ready(function()

/**************************************************************************
**************************************************************************
					FUNCTION LIST
**************************************************************************
**************************************************************************/

// ******************************************************** Opacity IE / Other

var opacityVariables = function(showOrHide){

	if(jQuery.browser.msie) {
		if(showOrHide == 'show') { return 'show'; } else { return 'hide'; }
	} else {
		if(showOrHide == 'show') { return '1'; } else { return '0'; }
	}

}

// ******************************************************** Opacity IE / Other

// ******************************************************** User login

var logmein = function(){
	
	$('#loginFormUpdate').html("Sending...").fadeTo("slow", 1);
	
	var loginVariables = $('#formLogin').serialize();
	var loginUrl = 'aGlobal';
			$.ajax({
				type: "POST",
				url: loginUrl,
				data: loginVariables,
				success: function(msg){
					if(msg != 'ok') {
						$('#message').html(msg);
						alertValidationBtn('#message', 'Ok');
						new Boxy('#message', {modal: true});
						$('#loginFormUpdate').html("&nbsp;").fadeTo("slow", 0);
					} else {
						$('#menuTags').animate({opacity: opacityVariables('hide')}, 1000).remove();
						reloadNav('Home');
						loadPage(470, 'Home');
						$('#recommendActions').css('display','block');
					}
				},
				error: function(xmlhttp) { alert("An error - xmlhttp.readyState: " + xmlhttp.readyState + "\nAn error - xmlhttp.status: " + xmlhttp.status); }
			});

}

// ******************************************************** User login

// ******************************************************** User logout

var logmeout = function(){
	
			$.ajax({
				type: "POST",
				url: 'aGlobal',
				data: 'logout=1', 
				success: function(msg){
					window.location = msg;
				}
			});

}

// ******************************************************** User logout

// ******************************************************** Reload Nav

var reloadNav = function(where){
	
			$.ajax({
				type: "POST",
				url: 'includeNavMain.php',
				data: 'whereTo=' + where,
				success: function(data){
					$('#contentNav').html(data);
				}
			});

}

// ******************************************************** Reload Nav

// ******************************************************** Function Load Page

var loadPage = function(pageWidth, pageName){
	
	$('.tipsy').remove(); // hide tips that may have reappeared
	
	var pageUrl = 'page' + pageName + 'Main.php';
	var menuTo = '#nav' + pageName;
	
	var pageWidthMenu = pageWidth - 20;
	
	var divh = $('#contentContent').height();

	$('#contentContent').animate({opacity:opacityVariables('hide')}, 300, 
		function(){ 
    		$('#contentNav a.active').removeClass('active'); 
    		$('#contentFrame').height(divh+50+44); // 44 = height of navigation
    		$('#contentContent').empty().height(divh);
    		$('#TopLogo').animate({width: (pageWidth + 22)}, 300);
    		$('#contentFrame').animate({width: (pageWidth + 2)}, 300,
    			function(){ 
    				//$('#contentContent').animate({width: pageWidth}, 300, // SAFARI
    				//$('#contentContent').animate({width: pageWidth}, 100,
    						//function(){ 
    							$(menuTo).addClass('active');
								$('#contentNav').css({width: pageWidthMenu});
    							$('#contentContent').css({width: pageWidth}).animate({opacity:opacityVariables('show')}, 300, 
    								function(){ 
    									// ******* AJAX
    									$.ajax({
    										cache: false, 
    										type: "POST",
    										url: pageUrl,
    										success: function(msg){
    											$('#dtip').remove(); $('.tipsy').remove(); // hide tips that may have reappeared
    											$('#contentContent').html(msg);
    											var contentHeight = $('#contentContentDynamique').height();
    											//$('#contentContent').append(contentHeight);
    											$('#contentFrame').animate({height: contentHeight+50+44}, 300);
    											$('#contentContent').animate({height: contentHeight}, 300);
												$('#contentContentDynamique').css({opacity: opacityVariables('hide')}).animate({opacity: opacityVariables('show')}, 500);
												// RELOAD NAV
												reloadNav(pageName);
												pageTracker._trackPageview("/"+pageName );
												//if(boxyAlert) { boxyAlert.unload(); }
    										}
    									});
    									// ******* AJAX
    								}
    							); //$('#contentContent').animate();
    						//} 
    				//);	//$('#contentContent').animate();	
    			}
    		); //$('#contentFrame').animate();
    	}
	); // $('#contentContent').animate();

}

// ******************************************************** Function Load Page

// ******************************************************** Function Load Page sub Nav

var loadSubPage = function(pageWidth, CatName, pageName, specialData){
	
	$('.tipsy').remove(); // hide tips that may have reappeared
	
	var pageUrl = 'page' + CatName + 'Sub' + pageName + '.php';
	var menuTo = '#nav' + CatName;
	
	var pageWidthMenu = pageWidth - 20;
	
	var divh = $('#contentContent').height();

	$('#contentContent').animate({opacity:opacityVariables('hide'), height: divh}, 300, 
		function(){ 
    		$('#contentNav a.active').removeClass('active'); 
    		$('#contentContent').html('');
    		$('#TopLogo').animate({width: (pageWidth + 22)}, 300);
    		$('#contentFrame').animate({width: (pageWidth + 2)}, 300,
    			function(){ 
    				//$('#contentContent').animate({width: pageWidth}, 300,
    						//function(){ 
    							$(menuTo).addClass('active');
								$('#contentNav').css({width: pageWidthMenu});
    							$('#contentContent').css({width: pageWidth}).animate({opacity:opacityVariables('show')}, 300, 
    								function(){ 
    									// ******* AJAX
    									$.ajax({
    										cache: false, 
    										type: "POST",
    										url: pageUrl,
    										data: specialData, 
    										success: function(msg){
    											$('#dtip').remove(); $('.tipsy').remove(); // hide tips that may have reappeared
    											$('#contentContent').html(msg);
    											var contentHeight = $('#contentContentDynamique').height();
    											$('#contentFrame').animate({height: contentHeight+50+44}, 300);
    											$('#contentContent').animate({height: contentHeight}, 300);
												$('#contentContentDynamique').css({opacity: opacityVariables('hide')}).animate({opacity: opacityVariables('show')}, 500);
												// RELOAD NAV
												reloadNav(CatName);
												pageTracker._trackPageview("/"+CatName+'_'+pageName );
    										}
    									});
    									// ******* AJAX
    								}
    							); //$('#contentContent').animate();
    				//		} 
    				//);	//$('#contentContent').animate();	
    			}
    		); //$('#contentFrame').animate();
    	}
	); // $('#contentContent').animate();

}

// ******************************************************** Function Load Page sub Nav

// ******************************************************** Loader
    var flobu ;
	var flobuFunction = function(element){
		$(function(){
			flobu = new flower_bubble ({
				base_obj: $( element ),
				base_dir: '/jquery',
				background: { css: '#fff', opacity: 0.5 },
				bubble: { image: 'bubble.png', width: 130, height: 98 },
				flower: { image: 'flower.gif', width: 32, height: 32 },
				block_mode: 'base_obj'
			}) ;
		}) ;
	}
// ******************************************************** Loader

// ******************************************************** Add dynamic textfield
var addDynamicElementNum = 0;

function addDynamicElement(divID, defaultTitle) {

		var divIDtoChange = '#' + divID;
		addDynamicElementNum++;
		var uniqueID = divID + addDynamicElementNum;
		$(divIDtoChange).append("\n<input type=\"text\" name=\"" + uniqueID + "_title\" id=\"" + uniqueID + "_title\" class=\"title\" style=\"opacity: 0;\" value=\"" + defaultTitle + "\"></input><span class=\"removeTitle\" onclick=\"javascript:$('input[name=" + uniqueID + "_title]').remove(); $(this).remove();\">&nbsp;</span>");
		
		var contentHeight = $('#contentContentDynamique').height();
		$('#contentFrame').animate({height: contentHeight+50+44}, 300);
		$('#contentContent').animate({height: contentHeight}, 300);
		var newInputTitle = '#' + uniqueID + '_title';
		//var newInputDescription = '#' + uniqueID + '_description';
		$(newInputTitle).animate({opacity: opacityVariables('show')}, 300);
		
		//$(newInputDescription).animate({opacity: '1'}, 300);
		
		$("input[class=title]").toggleVal({focusClass: "inputLite", changedClass: "inputChanged"});
		/*
		$('.removeTitle').click(function(){
			$inputToDelete = $(this).prev();
			$inputToDelete.remove();
			$(this).remove();
		});
		*/
		$("#MenuEntreesList > input.title").autocomplete("jquery/autocomplete/autocomplete-ajax.php?t=entrees");
		$("#MenuPlatsList > input.title").autocomplete("jquery/autocomplete/autocomplete-ajax.php?t=plats");
		$("#MenuDessertsList > input.title").autocomplete("jquery/autocomplete/autocomplete-ajax.php?t=desserts");
}

// ******************************************************** Add dynamique textfield

// ******************************************************** Replace accents function
function stripVowelAccent(str) {
	var s=str;

	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
	/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
	/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
	/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

	var repChar=['A','a','E','e','I','i','O','o','U','u'];

	for(var i=0; i<rExps.length; i++)
	s=s.replace(rExps[i],repChar[i]);

	return s;
}
// ******************************************************** Replace accents function

// ******************************************************** Tip

var currentTitle = '';

var dtip = function(identifier, minWidth, maxWidth, arrow) {
	
    $(identifier).hover(
		function() {
			currentTitle = $(this).attr('alt');
			$(this).attr('title', '');
			
			getPosition = $(this).offset();
			getHeight = $(this).outerHeight();
			getWidth = $(this).outerWidth();
			
			switch (arrow) {
				case 'small-bottom':
                	$('body').append( '<div id="dtip"><img src="images/MenuTipsTopSmall.png" class="center">' + currentTitle + '</div>' );
                    $('#dtip').css({'top':(getPosition.top+getHeight+3)+'px', 'left':(getPosition.left)+'px', 'max-width':maxWidth+'px', 'min-width':minWidth+'px'});
                    //$('#dtip .center').css({'top':'-'+($(this).height())+'px', 'left':($(this).parent().width()/4)+'px'});
				break;
				case 'main-menu':
                	$('body').append( '<div id="dtip"><img src="images/MenuTipsTopSmall.png" class="center">' + currentTitle + '</div>' );
                    $('#dtip').css({
                    	'top':(getPosition.top+getHeight+3)+'px', 
                    	'left':(getPosition.left+getWidth/2-$('#dtip').width()/2)+'px', 
                    	'max-width':maxWidth+'px', 
                    	'min-width':minWidth+'px'
                    	}).addClass('mainMenu');
				break;
            }
			
			$('#dtip').fadeIn('slow');
		}, 
		function() {
		
			$('#dtip').fadeOut('fast').remove();
			//$(this).attr('title', currentTitle);
			
		}
	);

}
// ******************************************************** Tip

// ******************************************************** Boxy close button
var alertValidationBtn = function(what, text) {
	if($(what+' .boxyClose').text() != ' '+text) {
		$(what).append('<a onclick="Boxy.get(this).hide(); return false" class="boxyClose"><img src="jquery/boxy/images/close.png" alt="close" width="30" height="30" border="0" align="middle"/> '+text+'</a>');
	}
}
// ******************************************************** Boxy close button

// ******************************************************** Help 
var help = function(segment){

			$.ajax({
				type: "POST",
				url: 'Help',
				data: 'help=1&segment=' + segment,
				success: function(msg){
						$('#message').html(msg);
						alertValidationBtn('#message', 'Fermer');					
						helpBox = new Boxy('#message', {modal: true});
						
						if(segment == 'menus') {
							$('.boxy-content').css('max-width','700px');
							helpBox.center().resize(800,500);
						} else {
							$('.boxy-content').css('max-width','350px');
							helpBox.center().resize(350,350);
						}
						pageTracker._trackPageview("/help_"+segment );
						
				}
			});

}
// ******************************************************** Help 
