// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function toggleSortBy() {
  if ($('#search_sort_by_distance').is(':checked'))
    $('#postal_code').show();
  else
    $('#postal_code').hide();
}

function toggleSortByOnLoading() {
  if ($('#search_sort_by_distance').is(':checked'))  
    document.write("<div id='postal_code' class='required' style=''>")
  else
    document.write("<div id='postal_code' class='required' style='display: none;'>")
}

function toggleWebSite() {
  if ($('#vendor_account_type option:selected' ).text() == 'Particulier')
    $('#web_site_div').hide();
  else
    $('#web_site_div').show();
}

function toggleWebSiteOnLoading() {
  if ($('#vendor_account_type option:selected' ).text() == 'Particulier')
    document.write("<div id='web_site_div' class='required' style='display: none;'>")
  else
    document.write("<div id='web_site_div' class='required'>")
}

function toggleIsFree() {
  if ($('#ad_is_free').is(':checked')) {
    $('#ad_price').val('0.00');
    $('#ad_price').attr('disabled', true);
    $('#ad_negociable').attr('disabled', true);
    $('#ad_is_taxable').attr('disabled', true);
  } else {
    $('#ad_price').attr('disabled', false);
    $('#ad_negociable').attr('disabled', false);
    $('#ad_is_taxable').attr('disabled', false);
  }
}


/* Set a new password - BEGIN */

function validateNewPasswordConfirmation (field,name,message) {
  if (validateRequired (field,name,message)) {
    var error = "";
    if ($F('change_password_form') != field) {
      return writeError(name, message +" ne correspond pas.");
    } else {
      return writeSuccess(name, "");
    }
  }
}

function validateFormNewPassword (field_name) {
  if (field_name == 'current_password')               { return validatePassword($F('change_password_form_current_password'),'current_password','Le mot de passe')}
  else if (field_name == 'new_password')              { return validatePassword($F('change_password_form_new_password'),'new_password','Le nouveau mot de passe')}
  else if (field_name == 'new_password_confirmation') { return validateNewPasswordConfirmation($F('change_password_form_new_password_confirmation'),'new_password_confirmation','La confirmation')}
  else {
    success = true;
    success = success && validateFormNewPassword('current_password');
    success = success && validateFormNewPassword('new_password');
    success = success && validateFormNewPassword('new_password_confirmation');
    return success;
  }
}

function validateCurrentPassword(field) {
  if (validatePassword($F('change_password_form_current_password'),'current_password','Mot de passe')) {
    // Check for an existing username
  //  new Ajax.Request('/users/check_username?login=' + field, {asynchronous:true, method: 'GET', evalScripts:true});    
  }
}


/* Set a new password - END */






// ***** JQuery POPUP Window 
  $(function() {
    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $("#dialog").dialog("destroy");
    
    var name = $("#name"),
      email = $("#email"),
      password = $("#password"),
      allFields = $([]).add(name).add(email).add(password),
      tips = $(".validateTips");

    function updateTips(t) {
      tips
        .text(t)
        .addClass('ui-state-highlight');
      setTimeout(function() {
        tips.removeClass('ui-state-highlight', 1500);
      }, 500);
    }

    function checkLength(o,n,min,max) {
      if ( o.val().length > max || o.val().length < min ) {
        o.addClass('ui-state-error');
        updateTips("Length of " + n + " must be between "+min+" and "+max+".");
        return false;
      } else {
        return true;
      }
    }

    function checkRegexp(o,regexp,n) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass('ui-state-error');
        updateTips(n);
        return false;
      } else {
        return true;
      }
    }
    
    $("#dialog-form").dialog({
      autoOpen: false,
      height: 300,
      width: 350,
      modal: true,
      buttons: {
        'Create an account': function() {
          var bValid = true;
          allFields.removeClass('ui-state-error');

          bValid = bValid && checkLength(name,"username",3,16);
          bValid = bValid && checkLength(email,"email",6,80);
          bValid = bValid && checkLength(password,"password",5,16);

          bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
          // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
          bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
          bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
          
          if (bValid) {
            $('#users tbody').append('<tr>' +
              '<td>' + name.val() + '</td>' + 
              '<td>' + email.val() + '</td>' + 
              '<td>' + password.val() + '</td>' +
              '</tr>'); 
            $(this).dialog('close');
          }
        },
        Cancel: function() {
          $(this).dialog('close');
        }
      },
      close: function() {
        allFields.val('').removeClass('ui-state-error');
      }
    });
    
    
    
    $('#create-user')
      .button()
      .click(function() {
        $('#dialog-form').dialog('open');
      });

  });

      
// ***** End of JQuery POPUP Window       


// Function for jCarousel
function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
        scroll: 2,
        auto: 0,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });
});




function showSearchDetails() {
  $('#collapse_show_icon').hide();
  $('#collapse_hide_icon').show();
  $('#div_search_criteria').slideDown("slow");
  
}

function hideSearchDetails() {
  $('#collapse_hide_icon').hide();
  $('#collapse_show_icon').show();
  $('#div_search_criteria').slideUp("slow");
}


function checkSearchField(){
  if ($('#search_search').val() == "  Entrez des mots clés") {
    $('#search_search').val("");      
    $('#search_search').css('color', "rgb(0, 0, 0)");
  }  
}


function toggle_tabs(name, has_picture){
  if(name == "pictures_album"){
    $('#tab_description').attr('src', "/images/tabs/tabs_description.png")
    $('#tab_location').attr('src', "/images/tabs/tabs_location.png")
    $('#tab_picture_album').attr('src', "/images/tabs/tabs_pictures_album_mo.png")
  }else if (name == "location"){
    $('#tab_description').attr('src', "/images/tabs/tabs_description.png")
    $('#tab_picture_album').attr('src', "/images/tabs/tabs_pictures_album.png")
    $('#tab_location').attr('src', "/images/tabs/tabs_location_mo.png")    
  }else {
    $('#tab_picture_album').attr('src', "/images/tabs/tabs_pictures_album.png")    
    $('#tab_location').attr('src', "/images/tabs/tabs_location.png")    
    $('#tab_description').attr('src', "/images/tabs/tabs_description_mo.png")
  }
  
  if (has_picture == false){
    $('#tab_picture_album').attr('src', "/images/tabs/tabs_pictures_album_na.png")
    $("#tab_of_pictures").removeAttr("href");
    $("#tab_of_pictures").removeAttr("onclick");
    $("#tab_of_pictures").css('cursor', "default"); 
  }
}

function set_a_default_image(){
  if (($("input[name='radio_name']:checked").val() == null) && ($("input[name='default_image']").length > 0)) {
    $("input[name='default_image']").first().click();
  }  
}



