$(document).ready(
	function()
	{
		$("#index_moteur").tabs();
		$("#tab_client").tabs();
	})
;

//gestion event player flash promo
myListener = new Object();

myListener.onInit = function()
{
	document.getElementById("myFlash").SetVariable("method:setUrl", "http://louerouacheter.com/flash/LouerOuAcheter.com.flv")
	document.getElementById("myFlash").SetVariable("method:play", "");
};

myListener.onClick = function(){};
myListener.onKeyUp = function(pKey){};
myListener.onFinished = function()
{
	close_intro('nostop');
};

myListener.onUpdate = function(){};


function changeImageOver(obj,image)
{
	$(obj).attr("src", '/images/'+image+'_hover.png');
}

function changeImageOut(obj,image)
{
	$(obj).attr("src", '/images/'+image+'.png');
}

//Affiche/masque les criteres suivant le critere select selectionner
function afficheCriteresCritere(categorie_id, critere_id)
{
	var selectedElement = $('#cat_'+categorie_id+'_'+critere_id).val();
	$(".critere").css("display", "none");
	$(".cat_"+selectedElement).css("display", "inherit");
}

function inialiseSWFUpload(upload_url)
{
	var swfu = new SWFUpload(
	{
		upload_url :  upload_url,
		//post_params: {"PHPSESSID": "<?php echo session_id(); ?>"},
		flash_url :  "/js/swfupload/swfupload.swf",
		flash9_url :   "/js/swfupload/swfupload_fp9.swf",
				 
		file_size_limit : "10 MB",
		file_types : "*.jpg;*.jpeg",
		file_types_description : "JPG Images",
		file_upload_limit : 0,

		button_placeholder_id : "swfUploadButton",
		button_image_url: "/images/fond_noir.png",
		button_width: "65",
		button_height: "29",
		button_text: '<span class="ajouter_photo">Ajouter...</span>',
		button_text_style : ".ajouter_photo { font-size: 14px; font-weight:bold; }",
		button_text_left_padding : 3,
		button_text_top_padding : 4,
		file_queue_limit : "0",

		// Event Handler Settings - these functions as defined in Handlers.js
		//  The handlers are not part of SWFUpload but are part of my website and control how
		//  my website reacts to the SWFUpload events.
		swfupload_preload_handler : preLoad,
		swfupload_load_failed_handler : loadFailed,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,

		custom_settings : {
			upload_target : "divFileProgressContainer"
		}
	}
	);
}

function publicInialiseSWFUpload(nb_photo_presente)
{
	swfu = new SWFUpload(
	{
		upload_url :  "http://www.louerouacheter.com/poster-une-annonce/upload",
		flash_url :  "/js/swfupload/swfupload.swf",
		flash9_url :   "/js/swfupload/swfupload_fp9.swf",

		file_size_limit : "10 MB",
		file_types : "*.jpg;*.jpeg",
		file_types_description : "JPG Images",
		file_upload_limit : 3 - nb_photo_presente,

		button_placeholder_id : "swfUploadButton",
		button_width: "251",
		button_height: "29",
		button_text: '<span class="ajouter_photo">Charger une photo (3 photos maximum)</span>',
		button_text_style : ".ajouter_photo { font-size: 14px; font-weight:bold; text-decoration: underline; }",
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_text_left_padding : 3,
		button_text_top_padding : 4,
		file_queue_limit : "3",

		// Event Handler Settings - these functions as defined in Handlers.js
		//  The handlers are not part of SWFUpload but are part of my website and control how
		//  my website reacts to the SWFUpload events.
		swfupload_preload_handler : preLoad,
		swfupload_load_failed_handler : loadFailed,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadCompleteWithoutReload,

		custom_settings : {
			upload_target : "divFileProgressContainer"
		}

	}
	);

}

//Ajoute aux favoris
function addFavoris(url)
{
	if( navigator.appName != 'Microsoft Internet Explorer' )
	{
		window.sidebar.addPanel(url, url ,"");
	}
	else
	{
		window.external.AddFavorite(url,url);
	}
}

//Affiche les infos complètes ou restreintes d'un annonceur voulant déposer une annonce
function possedeCompte()
{
	var value = ( $('#annonce_possede_compte_0:checked').val());

	if( value == 0)
	{
		$(".possede_compte_non").css("display", "inherit");
		$(".possede_compte_oui").css("display", "none");
	}
	else
	{
		value = ( $('#annonce_possede_compte_1:checked').val());
		if( value == 1)
		{
			$(".possede_compte_non").css("display", "none");
			$(".possede_compte_oui").css("display", "inherit");
		}
	}

}

//Suppression de la photo stocké en session
function delete_photo()
{
	if( confirm('Supprimer les photo ?') )
	{
		$.ajax({
			url: 'http://www.louerouacheter.com/poster-une-annonce/delete-photo',

			success: function(data) {
				$('#thumbnails').html('');
				swfu.setFileUploadLimit(swfu.settings.file_upload_limit + 3);
				$('#supprimer_photo').hide();
				$('.progressBarStatus').html('');
			}
		});
	}		
}

function check_moteur_recherche()
{
	var cpt_erreur = 0;

	$(".moteur_erreur").each(function()
	{
	
		if( $(this).html() != '' )
			cpt_erreur++;
	});

	$(".moteur_erreur_global").each(function()
	{
		if( $(this).html() != '' )
			cpt_erreur++;
	});

	$(".moteur_erreur_cp").each(function()
	{
		if( $(this).html() != '' )
			cpt_erreur++;
	});

	if( cpt_erreur == 0)
		return true;
	else
	{
		alert( 'Votre saisie est erronée. Veuillez corriger les erreurs indiquées en rouge.');
		return false;
	}

}

function check_moteur_recherche_cp()
{
	var cp = $('#cp').val();
	var erreur = false;

	if( cp.length > 0 && cp.length != 5)
	{
		$('#cp_erreur').html('Le code postal saisi doit être composé de 5 chiffres');
		erreur =true;
		$('#cp_erreur').show();
	}

	if(  cp.length > 0 && !IsNumeric(cp) )
	{
		$('#cp_erreur').html('Le code postal saisi doit être un nombre');
		erreur =true;
		$('#cp_erreur').show();
	}

	if( !erreur )
	{
		$('#cp_erreur').html('');
		$('#cp_erreur').hide();
	}
	
	return 0;
}

function check_moteur_recherche_ray()
{
	var cp = $('#cp').val();
	var erreur = false;

	if( cp.length != 5)
		erreur =true;

	if(  cp.length > 0 && !IsNumeric(cp) )
		erreur =true;

	if( !erreur )
	{
		$('#cache_rayon_km').hide();
	}
	else
	{
		$('#cache_rayon_km').show();
		$('#ray').val('');
	}

	return 0;
}

function check_moteur_recherche_cp2()
{
	var cp = $('#cp2').val();
	var erreur = false;

	if( cp.length > 0 && cp.length != 5)
	{
		$('#cp2_erreur').html('Le code postal saisi doit être composé de 5 chiffres');
		erreur =true;
		$('#cp2_erreur').show();
	}

	if(  cp.length > 0 && !IsNumeric(cp) )
	{
		$('#cp2_erreur').html('Le code postal saisi doit être un nombre');
		erreur =true;
		$('#cp2_erreur').show();
	}

	if( !erreur )
	{
		$('#cp2_erreur').html('');
		$('#cp2_erreur').hide();
	}

	return 0;
}

function check_moteur_recherche_ray2()
{
	var cp = $('#cp2').val();
	var erreur = false;

	if( cp.length != 5)
		erreur =true;

	if(  cp.length > 0 && !IsNumeric(cp) )
		erreur =true;

	if( !erreur )
	{
		$('#cache_rayon_km2').hide();
	}
	else
	{
		$('#cache_rayon_km2').show();
		$('#ray2').val('');
	}

	return 0;
}


function check_moteur_recherche_critere(input, name)
{
	var from = $('#'+input+'_from').val();
	var to = $('#'+input+'_to').val();

	var erreur = false;

	if( from.length > 0)
	{
		if( !IsNumeric(from) )
		{
			$('#'+input+'_from_erreur').html('Ce champ doit être un nombre');
			$('#'+input+'_from_erreur').show();
			erreur = true;
		}
		else
		{
			$('#'+input+'_from_erreur').html('');
			$('#'+input+'_from_erreur').hide();
		}
	}
	else
	{
		$('#'+input+'_from_erreur').html('');
		$('#'+input+'_from_erreur').hide();
	}

	if( to.length > 0)
	{
		if( !IsNumeric(to) )
		{
			$('#'+input+'_to_erreur').html('Ce champ doit être un nombre');
			$('#'+input+'_to_erreur').show();
			erreur = true;
		}
		else
		{
			$('#'+input+'_to_erreur').html('');
			$('#'+input+'_to_erreur').hide();
		}
	}
	else
	{
		$('#'+input+'_to_erreur').html('');
		$('#'+input+'_to_erreur').hide();
	}

	if( to.length > 0 && from.length > 0 && erreur == false )
	{
		from = parseInt(from);
		to = parseInt(to);
		if( from > to )
		{
			$('#'+input+'_erreur').html('Le maximum est plus petit que le minimum');
			$('#'+input+'_erreur').show();
		}
		else
		{
			$('#'+input+'_erreur').html('');
			$('#'+input+'_erreur').hide();
		}
	}
	else
	{
		$('#'+input+'_erreur').html('');
		$('#'+input+'_erreur').hide();
	}


	return 0;
}

function IsNumeric(text)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

	for (i = 0; i < text.length && IsNumber == true; i++)
	{
		Char = text.charAt(i);
		if (ValidChars.indexOf(Char) == -1)
		{
			IsNumber = false;
		}
	}
	return IsNumber;

}


function creer_lien_recherche_detaille2()
{
	var value_select = $('#c2').val();
	if( value_select != '')
		$('#recherche_detaille2').show();
	else
		$('#recherche_detaille2').hide();
}

function creer_lien_recherche_detaille()
{
	var value_select = $('#c').val();
	if( value_select != '')
		$('#recherche_detaille').show();
	else
		$('#recherche_detaille').hide();
}


function moteur_form_submit(id)
{
	$('#'+id).submit();
}


function recherche_achat()
{
	$('#onglet_j_achete a').attr('href', '#j_achete');
	$('#table_chargement').show();
	$('#'+'form_achat').submit();
}

function recherche_location()
{
	$('#onglet_je_loue a').attr('href', '#je_loue');
	$('#table_chargement').show();
	$('#'+'form_location').submit();
}

function click_j_achete()
{
	$('#img_j_achete').attr("src", "/images/j_achete_gros.gif") ;
	$('#img_je_loue').attr("src", "/images/je_loue.gif") ;
}

function click_je_loue()
{
	$('#img_j_achete').attr("src", "/images/j_achete.gif");
	$('#img_je_loue').attr("src", "/images/je_loue_gros.gif");
}

//Ajoute une annonce à la selection de l'utilisateur
function ajout_selection(id,subdomain)
{
	//Check si l'utilisateur est logger
	$.ajax({
			url: 'http://'+subdomain+'.louerouacheter.com/'+id+'/annonce-ajout-selection',
			//url: 'http://localhost/annonce/ajout-selection/'+id,
			cache : false,
			success: function(data)
			{
				//Si user bien authentifier, on ajoute l'annonce à la selection
				if( data == '1' )
				{
					$("#ajout_selection").effect('transfer',{to: "#header_compte", className: 'ui-effects-transfer'},1200,callback);
				}
				else
				{
					if( data == '2' )
					{
						alert('Cette annonce fait déjà partie de votre sélection');
					}
					else
					{
						if( data == '3' )
						{
							$.fancybox({
								//'href'			   : 'http://localhost/mon-compte/login-box',
								'href'			   : 'http://'+subdomain+'.louerouacheter.com/mon-compte/login-box',
								'title'   		   : 'Identification',
								'height' : 380,
								'width' : 760,
								'transitionIn'		: 'fade',
								'transitionOut'	: 'fade',
								'type'				: 'iframe'
							});
						}
						else
							alert("Une erreur s'est produite lors de l'ajout à la sélection");
					}
				}
			}
		});
}

function callback()
{
	setTimeout(function()
	{
		$("#effect:hidden").removeAttr('style').hide().fadeIn();
	}, 1000);
}

function closeFancyBox()
{
  $.fancybox.close();

  $('#ajout_selection').click();
}

//Appel page ajax permettant de previsualiser les infos saisies sur une page annonce
function previsualisation()
{
	var urlAjax = 'http://www.louerouacheter.com/annonce/ajax-previsualisation';

	//récupère les infos saisies dans le formulaire et les passe à la page Ajax
	//les photos sont gerer côté serveur car stocké en session
	rubrique = encodeURIComponent($('#annonce_categorie_id').val());
	commune = encodeURIComponent($('#annonce_commune_id').val());
	titre = encodeURIComponent($('#annonce_name').val());
	description = encodeURIComponent($('#annonce_description').val());
	achat = encodeURIComponent($('#annonce_achat').val());
	url_video = encodeURIComponent($('#annonce_url_video').val());

	//liste de critere

	criteres ='';
	prix= '0';
	$('.critere_cat').each(function(index)
	{
		tmp = $(this).attr("name").split('_');
		if( tmp.length >= 2 )
		{
			if(  tmp[0] == 'prix' )
			{
				id = tmp[1];
				criteres += '&prix_' + id + '=' + encodeURIComponent($(this).val());
				prix = $(this).val();
				if(prix == '' ) prix = '0';
			}
			else
			{
				if( tmp.length == 3 )
				{
					id = tmp[2];
					if( tmp[1] == 'select' )
						criteres += '&cs_' + id + '=' + encodeURIComponent($(this).val());
					else
						if( tmp[1] == 'libre' )
							criteres += '&cl_' + id + '=' + encodeURIComponent($(this).val());
				}
			}
		}
	});

	if(rubrique != '' && commune != '' && titre != '' && description != '' && achat != '' && prix != '')
	{

		urlAjax += '?rubrique='+rubrique+'&commune='+commune+'&titre='+titre+'&achat='+achat+'&url_video='+url_video+'&description='+description+criteres;

		$.ajax({
				url: urlAjax,
				cache : false,
				success: function(data)
				{
					$.fancybox({
					href				: 'http://www.louerouacheter.com/annonce/previsualisation',
					'title'   		   : 'Prévisualisation',
					'height' : 680,
					'width' : 800,
					'transitionIn'		: 'fade',
					'transitionOut'	: 'fade',
					'type'				: 'iframe'
					});
				}
			});
	}
	else
		alert('Certains champs obligatoires (*) ne sont pas remplis.');
}


/** ferme flash d'intro + traitement **/
function close_intro(dt)
{
	var dt2=new  Date();

	if( dt != "nostop" )
		time = (dt2.getTime()-dt.getTime());
	else
		time = "nostop";

	$.ajax({
				url: 'http://www.louerouacheter.com/passer-intro',
				data: "time="+time,
				cache : false
			});
	
	$('#flash_promo').html('');
	$('#flash_promo').hide();
	$('#flash_promo_fond').html('');
	$('#flash_promo_fond').hide('');
}

function check_option()
{
	var check = false;

	$(".checkbox_option").each(function()
	{
		if( $(this).attr("checked") )
			check = true;
	});

	if( !check )
		alert('Vous devez choisir au moins une option avant de valider votre sélection.');

	return check;
}

function click_ray()
{
	//if( $('#cache_rayon_km').css('display') == 'none')
		alert('Saisissez un code postal valide pour pouvoir faire une recherche aux alentours .');
}

function click_ray2()
{
	//if( $('#cache_rayon_km2').css('display') == 'none')
		alert('Saisissez un code postal valide pour pouvoir faire une recherche aux alentours .');
}

function redirect_photo(url)
{
	location.href=url;
}

function changeImg(obj, path)
{
	var name = $(obj).attr("src").split('/');
	var vignette =  name[name.length - 1];
	vignette = vignette.substr(0,vignette.length-5);
	vignette = vignette+'.jpg';
	$("#detail_annonce_main_photo").attr("src",path + vignette);
}

//Affiche/masque la liste d'option sur le detail d'une annonce
function hide_option_annonce()
{
	$('#liste_option_annonce ul').hide('blind');
	$('#fleche_up').hide();
	$('#fleche_down').show();
}
function show_option_annonce()
{
	$('#liste_option_annonce ul').show('blind');
	$('#fleche_up').show();
	$('#fleche_down').hide();
}
