// JavaScript Document
var globalA;
var globalForm="";

$(document).ready(function()	{
	$("input:text").blur(function(){
		if($(this).attr("format")=="up"){
			a=($(this).fieldValue()).toString();
			a=noAccent(a);
			$(this).attr('value', a.toUpperCase());
	}});
});

var utf8 = {
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

function noAccent(stringItem) {
	var accent = new Array(192, 193, 194, 195, 196, 197, 224, 225, 226, 227, 228, 229, 210, 211, 212, 213, 214, 216, 242, 243, 244, 245, 246, 247, 200, 201, 202, 203, 232, 233, 234, 235, 199, 231, 204, 205, 206, 207, 236, 237, 238, 239, 217, 218, 219, 220, 249, 250, 251, 252, 255, 209, 266);
	var no_accent = new Array("A", "A", "A", "A", "A", "A", "a", "a", "a", "a", "a", "a", "O", "O", "O", "O", "O", "O", "o", "o", "o", "o", "o", "o", "E", "E", "E", "E", "e", "e", "e", "e", "C", "c", "I", "I", "I", "I", "i", "i", "i", "i", "U", "U", "U", "U", "u", "u", "u", "u", "y", "N", "n");
	if (stringItem && stringItem!= "") {
		for(i=0;i<accent.length;i++)
		{
			var reg=new RegExp(String.fromCharCode(accent[i]),"g");
			stringItem = stringItem.replace(reg, no_accent[i]);
		}
	}
	return stringItem;
}

function showResponse2(responseText, statusText)  {
	alert(responseText);
}

function showResponse(responseText, statusText)  {
	answer=$('input[name="destination"]').fieldValue();
	answer=answer.toString();
	sessLang=getSessionValue("session_language");
	switch(answer) {
		case "testimonial":
			alert(simpleText("testmSentText"));
			if(sessLang=="fr") { window.location="/cheval/cheval.html";}
			if(sessLang=="en") { window.location="/horses/horses.html";}
			if(sessLang=="de") { window.location="/pferde/pferde.html";}
			break
		case "contact":
			alert(simpleText("sentEmail"));
			if(sessLang=="fr") { window.location="/cheval/cheval.html";}
			if(sessLang=="en") { window.location="/horses/horses.html";}
			if(sessLang=="de") { window.location="/pferde/pferde.html";}
			break
		case "orderChq,profil2":
			if(sessLang=="fr") { window.location="/cheval/confirmation-commande.html";}
			if(sessLang=="en") { window.location="/horses/order-confirm.html";}
			if(sessLang=="de") { window.location="/pferde/bestellungsbestatigung.html";}
			break;
		case "horse_mail_send":
			if(responseText!="") {
				responseText=responseText.split(/;/g);
				request="_=8&__="+responseText[0]+"&___=";
				for(i=1;i<responseText.length;i++) {
					request+=responseText[i]+"|";
					i++;
					request+=responseText[i];
					if(i<(responseText.length-1)) {
						request+="||";
					}
				}
				var sT;
				$.ajax({
					type: "POST",
					url: "/phpInc/mailer.php",
					dataType: "html",
					data: request,
					async: true,
					success: function(returnHTML) {
						sT=returnHTML;
					}});
			}
			alert(simpleText("sent_mail"));
			if(sessLang=="fr") { window.location="/cheval/email-list.html";}
			if(sessLang=="en") { window.location="/horses/email-list.html";}
			if(sessLang=="de") { window.location="/pferde/email-list.html";}
			break;
		case "action":
			window.location="index.php?template=2&form="+responseText;
			break;
		case "profilForm":
			alert(simpleText("horseRecordOK"));
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
		case "simpleAdd":
			alert(simpleText("horseAddOK2"));
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
		case "etalon":
		case "pouliniere":
		case "avendre":
			alert(simpleText("horseAddOK"));
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
		case "etalon_update":
		case "pouliniere_update":
		case "avendre_update":
			alert(simpleText("horseAddUpdateOK"));
			if(sessLang=="fr") { window.location="/cheval/miseajour-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/update-horse-ad.html";}
			if(sessLang=="de") { window.location="/pferde/aktualisierung-pferde-anzeige.html";}
			break;
		case "publicite":
			alert(simpleText("horseAddOK"));
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
		case "smallAd":
			alert(simpleText("horseAddOK"));
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
		case "website":
			alert(simpleText("horseAddOK"));
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
		case "freeSubscription":
			// Envoi du mail de confirmation de fin de commande.
			if(responseText!="") {
				responseText=responseText.split(/;/g);
				request="_=8&__="+responseText[0]+"&___=";
				for(i=1;i<responseText.length;i++) {
					request+=responseText[i]+"|";
					i++;
					request+=responseText[i];
					if(i<(responseText.length-1)) {
						request+="||";
					}
				}
				var sT;
				$.ajax({
					type: "POST",
					url: "/phpInc/mailer.php",
					dataType: "html",
					data: request,
					async: true,
					success: function(returnHTML) {
						sT=returnHTML;
					}});
				if (!sT || sT=="") {
					retMail=$('input[name="mail"]').fieldValue();
					$.ajax({
						type: "POST",
						url: "/phpInc/confirmSubscribtionMailing.php",
						dataType: "html",
						data: "_="+retMail,
						async: true
					});
				};
				alert(simpleText("sentFreeSubMail1")+$('input[name="mail"]').fieldValue()+"\n"+simpleText("sentFreeSubMail2"));
				window.location="/cheval/choix-annonce-cheval.html";
			}
			break;
		default:
			if(sessLang=="fr") { window.location="/cheval/choix-annonce-cheval.html";}
			if(sessLang=="en") { window.location="/horses/horse-advertisement-choice.html";}
			if(sessLang=="de") { window.location="/pferde/pferde-anmeldung-wahl.html";}
			break;
	}
} 

function simpleText(itemName) {
	$.ajax({
		type: "POST",
		url: "/phpInc/ajax_simple_text_display.php",
		dataType: "html",
		data: "_="+itemName,
		async: false,
		success: function(returnHTML) {
			sT=returnHTML;
		}});
	return(sT);
}

function mustBeChoice(rule) {
	blocked=0;
	if (rule!="") {
		rule=rule.toString();
		rules=rule.split(/;;/g);
	}
	source=rules[0];
	target=rules[1];
	condition=rules[2];
	if (condition!="") {
		condition=condition.toString();
		conditions=condition.split(/;/g);
	}
	for(i=0;i<conditions.length;i++) {
		values=conditions[i].split(/:/g);
		if($('input[name="'+source+'"]').fieldValue()==values[0]) {
			$('select[name="'+target+'"]').attr('value', values[1]);
			blocked=1;
		}
	}
	if(blocked!=0) {
			$('select[name="'+target+'"]').attr('disabled', true);
	} else {
			$('select[name="'+target+'"]').attr('disabled', false);
	}
}

function other(field) {
	if($('select[name="'+field+'"]').fieldValue()=="other") {
		valid=$('select[name="'+field+'"]').attr('valid');
		cName=$('select[name="'+field+'"]').attr('cName');
		$('select[name="'+field+'"]').attr('name', field+'_old');
		$('select[name="'+field+'_old"]').attr('valid', 0);
		$('select[name="'+field+'_old"]').after("<br/><span id='"+field+"SP'><input type='text' cName='"+cName+"' valid='"+valid+"' name='"+field+"' onBlur='emptyVerify(\""+field+"\")'/></span>");
		var focusedItem=$('input[name="'+field+'"]').get(0);
		focusedItem.focus();
		$('input[name="'+field+'"]').focus();
	}
}

function emptyVerify(field) {
		if ((!($('input[name="'+field+'"]').fieldValue()))||($('input[name="'+field+'"]').fieldValue()=="")) {
			$('span[id="'+field+'SP"]').empty();
			$('select[name="'+field+'_old"]').attr('name', field);
			$('select[name="'+field+'"]').attr('value', '');
		}
}

function fileValidate(formData, jqForm, options) {
	var verifyF=$('input[name="coveringContract"]').fieldValue();
	verifyF=verifyF.toString();
	var verifyExt=verifyF.split(/\./g);
	a=(verifyExt.length)-1;
	ext=(verifyExt[a]).toLowerCase();
	
	if ((ext!='doc')&&(ext!='rtf')&&(ext!='pdf')) {
		alert(simpleText("verifExtFile"));
		return false;
	} else {
		$('#waitUpload').jqmShow();
		return true;
	}
}

function photoValidate(formData, jqForm, options) {
	var verifyF=$('input[name="photo"]').fieldValue();
	verifyF=verifyF.toString();
	var verifyExt=verifyF.split(/\./g);
	a=(verifyExt.length)-1;
	ext=(verifyExt[a]).toLowerCase();
	
	if ((ext!='jpg')&&(ext!='jpeg')&&(ext!='gif')) {
		alert(simpleText("verifExtPhoto"));
		return false;
	} else {
		$('#waitUpload').jqmShow();
		return true;
	}
}

function msiteValidate(formData, jqForm, options) {
	a=$('p[name="pict"]');
	if(a.length<2){
		var verifyF=$('input[name="photo"]').fieldValue();
		verifyF=verifyF.toString();
		var verifyExt=verifyF.split(/\./g);
		a=(verifyExt.length)-1;
		ext=(verifyExt[a]).toLowerCase();
		if ((ext!='jpg')&&(ext!='jpeg')&&(ext!='gif')) {
			alert(simpleText("verifExtPhoto"));
			return false;
		} else {
			$('#waitUpload').jqmShow();
			return true;
		}
	} else {
		alert(simpleText("verifNbMSite"));
		return false;
	}
}

function videoValidate(formData, jqForm, options) {
	var verifyF=$('input[name="video"]').fieldValue();
	verifyF=verifyF.toString();
	var verifyExt=verifyF.split(/\./g);
	a=(verifyExt.length)-1;
	ext=(verifyExt[a]).toLowerCase();
	
	if ((ext!='flv')&&(ext!='mov')&&(ext!='avi')&&(ext!='divx')&&(ext!='mpg')&&(ext!='mpeg')&&(ext!='wmv')) {
		alert(simpleText("verifExtVideo"));
		return false;
	} else {
		$('#waitUpload').jqmShow();
		return true;
	}
}

function clearPict(parameters){
	$(document).ready(function(){
		a=parameters.split(/;/g);
		if(a[0]) { 
			$('div[id="'+a[0]+'"]').html(''); 
		}
		if(a[1]) { $('#'+a[1]).show(); }
		if($('p[name="pict"]').length==0) {
			$('div[id="adPhotoDiv"]').show();
			$('div[id="photoWSDiv"]').show();
		}
		photoVideoInit();
		if($('#mainForm').attr("type")=="simpleForm") {$("#photoDiv").show();}
		
   });
}

function clearVid(parameters){
	$(document).ready(function()	{
		a=parameters.split(/;/g);
		if(a[0]) { 
			$('div[id="v'+a[0]+'"]').html(''); 
		}
		if(a[1]) { $('#'+a[1]).show(); }
		photoVideoInit();
   });
}

function displayPhotoResult(responseText, statusText) {
	picts=responseText.split(/;;/g);
	nav=navigator.appName;
	if(nav.match(/microsoft/gi)) { pictNb=picts.length; } else { pictNb=(picts.length)-1; }
	for(i=0;i<pictNb;i++) {
		pict=picts[i].split(/;/g);
		if(pict[0]=="1") {
			form_get_contents("uploadedPict");
			addForm="<p><span class=\"center\">&nbsp;</span></p><div name='"+pict[2]+"' id='"+pict[2]+"'><p name='pict'><span class=\"left_long\"><img src=\"/phpInc/pict_redim.php?name=../pictures/"+pict[2]+"&size=92&mode=preserve&background=FDE9B2&_="+(Math.floor(Math.random() * 1000)+1)+";\" /><input name='picture[]' value='"+pict[2]+"' type='hidden'><input name='picture_file[]' value='"+pict[2]+"' type='hidden'></span><span class=\"right_long\">"+globalA+"<span class=\"all_mini\"><input type=\"button\" name=\"clearPhoto\" value=\""+simpleText('deletePict')+"\" onClick=\"clearPict('"+pict[2]+"');\" /></span><br/></span></p></div>";
		}
	}
	$('#waitUpload').jqmHide();
	if($('#insertPhoto').html()!=null) {
		$('#insertPhoto').before(addForm);
	} else {
		if($('#insertPhotoPlace').html()!=null) {
			$('#insertPhotoPlace').html(addForm);
			$('input[name="picture_rights_ok[]"]').attr("cName",simpleText("rightokmini"));
			$('input[name="picture_comment[]"]').attr("cName",simpleText("titre"));
			$('input[name="picture_name[]"]').attr("cName",simpleText("nom"));
			$('.supp').hide();
		}
	}
	photoVideoInit();
}

function displayAdvResult(responseText, statusText) {
	$('.supp').hide();
	picts=responseText.split(/;;/g);
	nav=navigator.appName;
	if(nav.match(/microsoft/gi)) { pictNb=picts.length; } else { pictNb=(picts.length)-1; }
	for(i=0;i<pictNb;i++) {
		pict=picts[i].split(/;/g);
		if(pict[0]=="1") {
			form_get_contents("uploadedAdv");
			addForm="<p name='pict'><span class=\"left_long\"><img src=\"/phpInc/pict_redim.php?name=../advertisement/"+pict[2]+"&size=92&mode=preserve&background=FDE9B2&_="+(Math.floor(Math.random() * 1000)+1)+";\" /><input name='picture' value='"+pict[2]+"' type='hidden'></span><span class=\"right_long\">"+globalA+"</span></p>";
		}
	}
	$('#waitUpload').jqmHide();
	$('#insertAdv').html(addForm);
	$('#next2').show();
}

function displayAdResult(responseText, statusText) {
	$('.supp').hide();
	picts=responseText.split(/;;/g);
	nav=navigator.appName;
	if(nav.match(/microsoft/gi)) { pictNb=picts.length; } else { pictNb=(picts.length)-1; }
	for(i=0;i<pictNb;i++) {
		pict=picts[i].split(/;/g);
		if(pict[0]=="1") {
			form_get_contents("uploadedAd");
			addForm="<div name='"+pict[2]+"' id='"+pict[2]+"'><p name='pict'><span class=\"left_long\"><img src=\"/phpInc/pict_redim.php?name=../pictures/"+pict[2]+"&size=92&mode=preserve&background=FDE9B2\" /><input name='picture' value='"+pict[2]+"' type='hidden'></span><span class=\"right_long\">"+globalA+"<span class=\"all_mini\"><input type=\"button\" name=\"clearPhoto\" value=\""+simpleText('delete')+"\" onClick=\"clearPict('"+pict[2]+"');\" /></span><br/></span></p></div>";
		}
	}
	$('#waitUpload').jqmHide();
	$('#insertPhotoPlace').html(addForm);
	$('#next2').show();
}


function displayWsResult(responseText, statusText) {
	$('.supp').hide();
	picts=responseText.split(/;;/g);
	nav=navigator.appName;
	if(nav.match(/microsoft/gi)) { pictNb=picts.length; } else { pictNb=(picts.length)-1; }
	for(i=0;i<pictNb;i++) {
		pict=picts[i].split(/;/g);
		if(pict[0]=="1") {
			form_get_contents("uploadedAdv");
			addForm="<p name='pict'><span class=\"left_long\"><img src=\"/phpInc/pict_redim.php?name=../pictures/"+pict[2]+"&size=92&mode=preserve&background=FDE9B2\" /><input name='picture' value='"+pict[2]+"' type='hidden'></span><span class=\"right_long\">"+globalA+"</span></p>";
		}
	}
	$('#waitUpload').jqmHide();
	$('#insertAdv').html(addForm);
	$('#next2').show();
}

function displayMSiteResult(responseText, statusText) {
	picts=responseText.split(/;;/g);
	nav=navigator.appName;
	if(nav.match(/microsoft/gi)) { pictNb=picts.length; } else { pictNb=(picts.length)-1; }
	for(i=0;i<pictNb;i++) {
		pict=picts[i].split(/;/g);
		if(pict[0]=="1") {
			form_get_contents("uploadedMSite");
			addForm="<div name='"+pict[2]+"' id='"+pict[2]+"'><p name='pict'><span class=\"left_msite\"><img src=\"/phpInc/pict_redim.php?name=../pictures/"+pict[2]+"&size=92&mode=preserve&background=FDE9B2&_="+(Math.floor(Math.random() * 1000)+1)+";\" /><input name='picture[]' value='"+pict[2]+"' type='hidden'><input name='picture_file[]' value='"+pict[2]+"' type='hidden'></span><span class=\"right_msite\">"+globalA+"<span class=\"all_mini\"><input type=\"button\" name=\"clearPhoto\" value=\""+simpleText('deletePict')+"\" onClick=\"clearPict('"+pict[2]+"');\" /></span><br/></span></p></div>";
		}
	}
	$('#waitUpload').jqmHide();
	$('#persoPict').before(addForm);
}


function displayVideoResult(responseText, statusText) {
	picts=responseText.split(/;;/g);
	nav=navigator.appName;
	if(nav.match(/microsoft/gi)) { pictNb=picts.length; } else { pictNb=(picts.length)-1; }
	for(i=0;i<pictNb;i++) {
		pict=picts[i].split(/;/g);
		if(pict[0]=="1") {
			form_get_contents("uploadedVideo");
			
			addForm="<div name='v"+pict[2]+"' id='v"+pict[2]+"'><p name='vid'><span class=\"left_long\"><img src=\"/templates/common/pictures/vidIcon.jpg\"><input name='video_file' value='"+pict[2]+"' type='hidden'><input name='movie[]' value='"+pict[2]+"' type='hidden'></span><span class=\"right_long\">"+globalA+"<span class=\"all_mini\"><input type=\"button\" name=\"clearVideo\" value=\""+simpleText('delete')+"\" onClick=\"clearVid('"+pict[2]+"');\" /></span><br/></span></p></div>";
		}
	}
	$('#waitUpload').jqmHide();
	$('#insertVideo').before(addForm);
	photoVideoInit();
}

function displayFileResult(responseText, statusText) {
	files=responseText.split(/;/g);
	if(files.length>1){
		addForm="<p name='file'><span class=\"left\">"+simpleText("haCoveringContract")+"</span><span class=\"right\">"+simpleText("uploaded")+"<input type=\"hidden\" name=\"covering_contract\" value=\""+files[2]+"\"/> <input type=\"button\" value=\""+simpleText("delete")+"\" class=\"photoButton\" onClick=\"javascript: deleteCCFile();\"></span></p>";
	} else {
		addForm="<p><span class=\"left\">"+simpleText("haCoveringContract")+"</span><span class=\"right\">"+simpleText("uploaderror")+" <input type=\"button\" value=\""+simpleText("reDo")+"\" class=\"photoButton\" onClick=\"javascript: deleteCCFile();\"></span></p>";
	}
	$('#waitUpload').jqmHide();
	$('#insertFile').html(addForm);
	$('#fileDiv').hide();
}

function deleteCCFile(){
	$('#insertFile').html("");
	$('#fileDiv').show();
}

function form_get_contents(formName) {
	$.ajax({
		type: "POST",
		url: "/phpInc/ajax_forms_display.php",
		dataType: "html",
		data: "_="+formName,
		async: false,
		success: function(returnValue) {
			globalA=returnValue.toString();
		}});
}

function mainSubmit() {
	$("select").each(function() {
		$(this).attr('disabled', false);
		});
    var options = { 
		beforeSubmit:  validate,  // pre-submit callback 
		success:       showResponse  // post-submit callback 
	};

	$('#mainForm').ajaxSubmit(options); 
	return false;
}

function formSubmit(formName) {
	$("select").each(function() {
		$(this).attr('disabled', false);
		});
    var options = { 
		beforeSubmit:  validate// ,  // pre-submit callback 
		//success:       showResponse  // post-submit callback 
	};

	$('#'+formName).ajaxSubmit(options); 
	return false;
}

function formSubmit2(formName) {
	$("select").each(function() {
		$(this).attr('disabled', false);
		});
    var options = { 
		beforeSubmit:  validate,  // pre-submit callback 
		success:       showResponse  // post-submit callback 
	};

	$('#'+formName).ajaxSubmit(options); 
	return false;
}

function uploadSubmit(formName) {
	formN=new Array("docForm",			"photoForm",			"adPhotoForm",		"wsPictForm",		"advForm",			"msitePictForm",		"videoForm");
	bS=   new Array("fileValidate",		"photoValidate",		"photoValidate",	"photoValidate",	"photoValidate",	"msiteValidate",		"videoValidate");
	sS=   new Array("displayFileResult","displayPhotoResult",	"displayAdResult",	"displayWsResult",	"displayAdvResult",	"displayMSiteResult",	"displayVideoResult");
	u=0;
	while(formN[u]){
		if(formName==formN[u]){
			bS0=bS[u];
			sS0=sS[u];
		}
		u++;
	}
	
	eval("var options = { beforeSubmit: "+bS0+", success: "+sS0+"};");

	$('#'+formName).ajaxSubmit(options); 
	return false;
}


function formatRound(value){
	// calcul de l'arrondi
	value=(Math.round(value*100))/100;
	decimal=Math.round((value-Math.floor(value))*100);
	integer=Math.floor(value);
	integer2string=integer+"";
	var nb=integer2string.length;
	for (var i=1;i<4;i++) {
		if (integer>=Math.pow(10,(3*i))) {
			a=integer2string.substring(0,nb-(3*i));
			integer2string=integer2string.substring(0,nb-(3*i))+" "+integer2string.substring(nb-(3*i));
		}
	}
	var decimToString=""; 
	for (var j=0;j<(2-decimal.toString().length);j++) {decimToString+="0";}
	decimToString=decimToString+decimal.toString();
	numberToString=integer2string+","+decimToString;
	return numberToString;
}