var uploadmanager;

var message1 = "Veuillez s'il vous pla\356t prendre connaissance des r\350gles d'utilisation du site, et confimer que vous d\351tenez les droits sur cette photo, et que celle-ci ne contrevient pas aux r\350gles d\351finies."; 
var message2 = "Seuls les fichiers jpg, png, jpeg et gif sont accept\351s"
var message3 = "Veuillez s\351lectionner une image.";
var g_currentEmail = 0;
var g_forceSection = "";


//----------------------------------------------------------------
//            Initialization
//----------------------------------------------------------------



jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.


if ($("#searchproximity").length>0) {
    $("input[name='words']").focus(searchWordsFocus);
    $("input[name='words']").blur(searchWordsUnfocus);
    $("input[name='postal']").focus(searchPostalFocus);
    $("input[name='postal']").blur(searchPostalUnfocus);
  }

  
  
  if ($("#upload_photo").length>0) {
    uploadmanager = new AjaxUpload('#upload_photo', {
    // Location of the server-side upload script
    // NOTE: You are not allowed to upload files to another domain
    action: '/ajax_postphoto.php',
    // File upload name
    name: 'userfile',
    
    // Submit file after selection
    autoSubmit: true,
    // The type of data that you're expecting back from the server.
    // HTML (text) and XML are detected automatically.
    // Useful when you are using JSON data as a response, set to "json" in that case.
    // Also set server response type to text/html, otherwise it will not work in IE6
    responseType: false,
    // Fired after the file is selected
    // Useful when autoSubmit is disabled
    // You can return false to cancel upload
    // @param file basename of uploaded file
    // @param extension of that file
    onChange: function(file, extension){
      if (! (extension && /^(jpg|png|jpeg|gif)$/.test(extension))){
          // extension is not allowed
          alert(message2);
          
          // cancel upload
          return false;
      }
      
      $("input[name='photoname']").val(file);
      
    },
    // Fired before the file is uploaded
    // You can return false to cancel upload
    // @param file basename of uploaded file
    // @param extension of that file
    onSubmit: function(file, extension) {
        var status = $("#checkphoto").attr('checked')?1:0;
      if ($("input[name='photoname']").val()=="") {
        alert(message3);
        $("input[name='photoname']").val(""); 
        return false;
      }
      else if (status==0) {
        alert(message1);
        $("input[name='photoname']").val(""); 
        return false;
      }
      else {
        uploadmanager.setData({"photook":status, "upload": "ok"});
      }
    },
    // Fired when file upload is completed
    // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
    // @param file basename of uploaded file
    // @param response server response
    onComplete: function(file, response) {
      var data = response.split("|");
      
      if (data[0]=="OK") {
          // replace the photo
          $("#photoimg").hide();
          $("#photocomment").show();
          
          
          // Set the picture
          var width = parseInt(data[2]);
          var height = parseInt(data[3]);
          var ratio = 1;
          if (width>570) {
            ratio = width/570;
            height /= ratio;
            width = 570;
          }
          
          $("input[name='ratio']").val(ratio);
          $("#testImage").attr("width", width);
          $("#testImage").attr("height", height);
          $("#testImage").attr("src", "/photos/" + data[1]);
          
          $("#testWrap").show();
                  
          // Erase the image
          $("input[name='photoname']").val(""); 
          if (mycropper) mycropper.remove();
          mycropper = new Cropper.ImgWithPreview( 'testImage', { previewWrap: 'photoelem', minWidth: 100, minHeight: 138, ratioDim: { x: 100, y: 138 }, onEndCrop: onEndCrop } );
      }
      else {
        var curmsg = data[1];
        curmsg = curmsg.replace("é", "\351");  
        alert(curmsg);
      }
      
    }
  }); 
  }

  
//----------------------------------------------------------------
//            Photo
//----------------------------------------------------------------
$("#validcrop").live("click", function(event) {
var x1 = $("input[name='x1']").val();
var y1 = $("input[name='y1']").val();
var x2 = $("input[name='x2']").val();
var y2 = $("input[name='y2']").val();
var ratio = $("input[name='ratio']").val();
  var data = {"x1":x1, "y1":y1, "x2":x2, "y2":y2, "ratio":ratio};
  $.post("/ajax_cropphoto.php", data, function(data) {
  if (data=="OK") alert("Votre photo a \351t\351 mise \340 jour");
    else alert("Votre session a expir\351. Veuillez vous reconnecter");
  }
  );
  
}
);
//----------------------------------------------------------------
//            Login
//----------------------------------------------------------------

function checkLogin(event) {
  var login = $("input[name='email']").val();
  var password = $("input[name='password']").val();
  
  
  var data = {"email":login, "password":password};
  $.post("/ajax_checklogin.php", data, loginResultReceived);
}

function loginResultReceived(data) {
  var message1 = "Votre email ou votre mot de passe ne sont pas corrects.";
  var message2 = "Vous \352tes maintenant connect\351.";
  var message3 = "Votre adresse email n'a pas encore  \351t\351 valid\351e. Veuillez s'il vous pla\356t v\351rifier vos emails, et suivre les instructions.";
  var result = eval(data);
  
  if (result==0) {
    $("#headerlogin").hide();
    $("#boutoninscription").hide();
    alert(message2);
  }
  else if (result==-21) alert(message3);
  else alert(message1);

}

$("#submitlogin").live("click", checkLogin);



//----------------------------------------------------------------
//            Annonce management
//----------------------------------------------------------------
function announceDelete(event) {
  
  var id = event.target.id.replace("delete", "");
  
  // Aks to remove the annonce
  $.post("/ajax_annonce.php", { id: id, action:"delete"}, function(data){
      // Hide the annonce
      $("#annonce"+id).hide("slow", function(){
      $("#annonce"+id).remove();
      
      // Display the no announce message
      if ($(".adcontainer").length==0) {
        $(".noadd").show();
      }
    });
  });
}

function announceEdit(event) {
  var id = event.target.id.replace("edit", "");
  document.location = "compte_editannonce.php?id=" + id;
}

function announceView(event) {
  var id = event.target.id.replace("view", "");
  document.location = "annonce.php?data=" + id ;
}

if ($.browser.msie) {
  $("select[name='onlinestatus']").live("click", function(event) {
  //var id = $("select[name='onlinestatus']").attr("id").replace("online", "");
  //var id = event.target.id.replace("online", "");
  var id = this.id.replace("online", "");
  var annonce = $("#annonce"+id);
  var curclass;
  var value = $("#online"+id).val();
                       
  // Change status
  $.post("/ajax_annonce.php", { id: id, action:"status", status: value }, function(data){
      if (value=="offline") {
        $(".adinfo", annonce).attr("class", "adinfo adunpublished");
        $(".adsingleaction", annonce).each(function(){
          curclass = $(this).attr("class");
          $(this).attr("class", curclass + " adsingleunpublished");
        });
      }
      else {
        $(".adinfo", annonce).attr("class", "adinfo");
        $(".adsingleaction", annonce).each(function(){
          curclass = $(this).attr("class");
          $(this).attr("class", curclass.replace("adsingleunpublished", ""));
        });
 
      }
  });
}
);
}


$("select[name='onlinestatus']").live("change", function(event) {
  //var id = $("select[name='onlinestatus']").attr("id").replace("online", "");
  //var id = event.target.id.replace("online", "");
  var id = this.id.replace("online", "");
  var annonce = $("#annonce"+id);
  var curclass;
  var value = $("#online"+id).val();
                       
  // Change status
  $.post("/ajax_annonce.php", { id: id, action:"status", status: value }, function(data){
      if (value=="offline") {
        $(".adinfo", annonce).attr("class", "adinfo adunpublished");
        $(".adsingleaction", annonce).each(function(){
          curclass = $(this).attr("class");
          $(this).attr("class", curclass + " adsingleunpublished");
        });
      }
      else {
        $(".adinfo", annonce).attr("class", "adinfo");
        $(".adsingleaction", annonce).each(function(){
          curclass = $(this).attr("class");
          $(this).attr("class", curclass.replace("adsingleunpublished", ""));
        });
 
      }
  });
}
);


  


function changeCategory(event) {
  var category = $("select[name='category']").val();
  var tmp = category.split("_");
  var level = tmp[1];
  var display = false;
  var value = 1;
  for(var i=0; i<11; i++) {
    if (level&value) {
      $("#advtype" + value).show();
      display = true;
    }
    else $("#advtype" + value).hide();    
    value *= 2;
  }
  if (display) $("#commentoption").show();
  else $("#commentoption").hide();
  
}


function chooseStudent(event) {
  var current = $("#searchstudent").attr("class");
  if (current=="searchoptionselect") return false;
  
  $("#searchprofessor").attr("class", "searchoption");
  $("#searchstudent").attr("class", "searchoptionselect");
  $("input[name='type']").val("student");
  $("input[name='gosearch']").trigger('click');
}
function chooseProfessor(event) {
  var current = $("#searchprofessor").attr("class");
  if (current=="searchoptionselect") return false;
  
  $("#searchstudent").attr("class", "searchoption");
  $("#searchprofessor").attr("class", "searchoptionselect");
  $("input[name='type']").val("prof");
  $("input[name='gosearch']").trigger('click');
}


$(".addelete").live("click", announceDelete);
$(".adedit").live("click", announceEdit);
$(".adview").live("click", announceView);
$("#searchstudent").live("click", chooseStudent);
$("#searchprofessor").live("click", chooseProfessor);


//----------------------------------------------------------------
//            Display announce
//----------------------------------------------------------------
function displayClientMessage(event) {
  $("input[name='name']").val("");
  $("input[name='email2']").val("");
  $("textarea[name='content']").val("");
  $("#aderroremail").hide();
  $("#aderrorname").hide();
  $("#admsgsent").hide();
  $("#aderrormsg").hide();
  $("#boxmailstudent").hide();
  $("#ademail").slideDown(1000);
}

function sendClientMessage(event) {
  var name = $("input[name='name']").val();
  var email = $("input[name='email2']").val();
  var content = $("textarea[name='content']").val();
  var id = $("input[name='id']").val();
  var security = $("input[name='security']").val();
  var antispam = $("input[name='antispam']").val();
  
  var data = {"id":id, "name":name, "email":email, "content":content, "antispam":antispam, "security":security};
  $.post("/ajax_clientemail.php", data, clientMessageSent);
}

function clientMessageSent(data) {
  var result = eval(data);
  if (result==0) {
    $("#ademail").slideUp(300);
    $("#admsgsent").slideDown(300);
  }
  if (result&1) $("#aderroremail").show();
  else $("#aderroremail").hide();
  if (result&2) $("#aderrorname").show();
  else $("#aderrorname").hide();
  if (result&4) $("#aderrormsg").show();
  else $("#aderrormsg").hide();
  if (result&8) $("#aderrorsecurity").show();
  else $("#aderrorsecurity").hide();
  
}

function categoryChanged(event)
{
  $("input[name='words']").val("Mots clefs");
}

function refreshSpamImage(event)
{
  $.get("/ajax_createspam.php", SpamChanged);
}
function SpamChanged(data)
{
  var id = eval(data);
  
  $("#spamimage").attr("src", "/images/antispam.php?id=" + id);
  $("input[name='antispam']").val(id);
}

$("#adwrite").live("click", displayClientMessage);
$("#adsend").live("click", sendClientMessage);
$("select[name='category']").live("change", categoryChanged);
$("#spamimage").live("click", refreshSpamImage);

//----------------------------------------------------------------
//            Search
//----------------------------------------------------------------
function searchWordsFocus(event)
{
  var elem = $("input[name='words']");
  if (elem.val()=="Mots clefs") elem.val("");
}
function searchWordsUnfocus(event)
{
  var elem = $("input[name='words']");
  if (elem.val()=="") elem.val("Mots clefs");
}
function searchPostalFocus(event)
{
  var elem = $("input[name='postal']");
  if (elem.val()=="Code Postal") elem.val("");
}
function searchPostalUnfocus(event)
{
  var elem = $("input[name='postal']");
  if (elem.val()=="") elem.val("Code Postal");
}




















});
  

//----------------------------------------------------------------
//            Image swap
//----------------------------------------------------------------
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}




