var selector_id = 0;

function getSelectorId(){
  return ++selector_id;
}

$(document).ready(function(){
  var urll = location.href;
  if(strpos(urll, '/post/sextip')) {
    var footer = $('.content-wrapper #footer').html();
    $('.content-wrapper #footer').remove();
    footer = '<div id="footer">' + footer + '</div>';
    $('.content-wrapper').after(footer);
  }
});

function createRootCategoriesSelector(cats){
  /*for (var i=0; i<$('.error ul li').length; i++) {
   if ($('.error ul li').eq(i).html().indexOf("Primary category") != -1) prim_cat_error = 'border: 1px solid red;'
   }
   if (!prim_cat_error) {
   prim_cat_error = '';
   }*/
  var id = getSelectorId();
  if (!document.getElementById('selectors'))
    $.create('div', {
      'id': 'selectors'
    }).appendTo('.body-field-wrapper');
  $.create('p', {
    'class': 'space-' + id
  }).appendTo('#selectors');
  /*$.create('div', {
    'class': 'break-line-1'
  }).appendTo('#selectors');*/
  if (id > 1) {
    $.create('label', {
      'for': 'edit-category-' + id
    }, 'Additional Category').appendTo('.space-' + id);
    $.create('a', {
      'id': 'remove-category-' + id,
      'href': '#'
    }, '[remove]').appendTo('.space-' + id);
    $("a#remove-category-" + id).click(function(){
      $('#edit-category-' + id).remove();
      $('#edit-category-' + id + '-1').remove();
      $('#edit-category-' + id + '-2').remove();
      $('#remove-category-' + id).remove();
      $('label[for=edit-category-' + id + ']').remove();
      $('p.space-' + id).remove();
      $('div#category-selector-' + id).remove();
      return false;
    });
  }
  else {
    $.create('label', {
      'for': 'edit-category-' + id,
      'id': 'primary-category'
    }, 'Primary Category:').appendTo('.space-' + id);
    $.create('div', {
      'class': 'description sextip-new-description'
    }, 'Once you select a top-level category, you will get an option to select subcategories: secondary and possibly trietary. Please make your selections as specific as possible. If your tip contains content that may belong to multiple categories, please click on "add another category" link below.').appendTo('.space-' + id);
    $.create('span', {
      'class': 'form-required',
      'title': 'This form is required'
    }, '*').appendTo('#primary-category');
  }
  $.create('div', {
    'id': 'category-selector-' + id,
    'class': 'category-selectors-wrapper'
  }).appendTo('.space-' + id);
  $.create('div', {
    'id': 'categor-wrapper-' + id,
    'class': 'categor-wrapper'
  }).appendTo('div#category-selector-' + id);
  $.create('select', {
    'id': 'edit-category-' + id,
    'class': 'first',
    'multiple': 'multiple',
    'size': 5
  }).appendTo('div#categor-wrapper-' + id);
  $("select#edit-category-" + id).change(function(){
    if (this.selectedIndex != -1) {
      createFirstLevelCategories(this.selectedIndex, id);
      $('#edit-category-' + id + '-2').remove();
      var arr = $(this).selectedOptions();
      if (arr.length > 1) {
        $(this).selectOptions(arr[0].value, true);
      }
    }
    else {
      $('#edit-category-' + id + '-1').remove();
      $('#edit-category-' + id + '-2').remove();
    }
  });
  if (!document.getElementById('adding-one-more-category')) {
    $.create('a', {
      'id': 'adding-one-more-category',
      'href': '#'
    }, 'Add another category').appendTo('.body-field-wrapper');
    $("a#adding-one-more-category").click(function(){
      createRootCategoriesSelector(cats);
      return false;
    });
  }
  for (var i = 0; i < cats.length; i++) {
    if (cats[i].parents == 0) {
      $.create('option', {
        'value': cats[i].tid,
        'id': cats[i].tid + '-' + id
      }, cats[i].name).appendTo('#edit-category-' + id);
    }
  }
}

function createFirstLevelCategories(index, id){
  var count = 0;
  if (!document.getElementById('edit-category-' + id + '-1')) {
    $.create('select', {
      'id': 'edit-category-' + id + '-1',
      'multiple': 'multiple',
      'size': 5
    }).appendTo('div#category-selector-' + id);
    $("select#edit-category-" + id + "-1").change(function(){
      if (this.selectedIndex != -1) {
        createSecondLevelCategories(this.selectedIndex, id);
        var arr = $(this).selectedOptions();
        if (arr.length > 1) {
          $(this).selectOptions(arr[0].value, true);
        }
        return false;
      }
      else {
        $('#edit-category-' + id + '-2').remove();
      }
    });
  }
  else {
    $('#edit-category-' + id + '-1').find('option').remove();
  }
  for (var i = 0; i < cats.length; i++) {
    if (parseInt(cats[i].parents) == parseInt(document.getElementById('edit-category-' + id).options[index].value)) {
      $.create('option', {
        'value': cats[i].tid,
        'id': cats[i].tid + '-' + id
      }, cats[i].name).appendTo('#edit-category-' + id + '-1');
      count++;
    }
  }
  if (count == 0)
    $('#edit-category-' + id + '-1').remove();
}

function createSecondLevelCategories(index, id){
  var count = 0;
  if (!document.getElementById('edit-category-' + id + '-2'))
    $.create('select', {
      'id': 'edit-category-' + id + '-2',
      'multiple': 'multiple',
      'size': 5,
      'class': 'third-category'
    }).appendTo('div#category-selector-' + id);
  else
    $('#edit-category-' + id + '-2').find('option').remove();
  $('select#edit-category-' + id + '-2').change(function(){
    var arr = $(this).selectedOptions();
    if (arr.length > 1) {
      $(this).selectOptions(arr[0].value, true);
    }
  });
  for (var i = 0; i < cats.length; i++) {
    if (parseInt(cats[i].parents) == parseInt(document.getElementById('edit-category-' + id + '-1').options[index].value)) {
      $.create('option', {
        'value': cats[i].tid,
        'id': cats[i].tid + '-' + id
      }, cats[i].name).appendTo('#edit-category-' + id + '-2');
      count++;
    }
  }
  if (count == 0)
    $('#edit-category-' + id + '-2').remove();
}

function rememberTipCategories(){
  var tid = '';
  $.create('br').appendTo('.body-field-wrapper');
  $.create('input', {
    'type': 'hidden',
    'id': 'categories-count',
    'name': 'count_categories',
    'value': selector_id
  }).appendTo('.body-field-wrapper');
  if ($('#edit-category-1 :selected').val())
    $('#edit-field-primary-0-value').val($('#edit-category-1 :selected').val());
  if ($('#edit-category-1-1 :selected').val())
    $('#edit-field-primary-0-value').val($('#edit-category-1-1 :selected').val());
  if ($('#edit-category-1-2 :selected').val())
    $('#edit-field-primary-0-value').val($('#edit-category-1-2 :selected').val());
  if (!$('#edit-category-1 :selected').val() && !$('#edit-category-1-1 :selected').val() && !$('#edit-category-1-2 :selected').val())
    $('#edit-field-primary-0-value').val('');
  for (var i = 1; i <= selector_id; i++) {
    if (document.getElementById('edit-category-' + i)) {
      if (document.getElementById('edit-category-' + i).selectedIndex == -1) {
        continue;
      }
      tid = document.getElementById('edit-category-' + i).options[document.getElementById('edit-category-' + i).selectedIndex].value;
    }

    if (document.getElementById('edit-category-' + i + '-1')) {
      if (document.getElementById('edit-category-' + i + '-1').selectedIndex != -1)
        tid = document.getElementById('edit-category-' + i + '-1').options[document.getElementById('edit-category-' + i + '-1').selectedIndex].value;
    }

    if (document.getElementById('edit-category-' + i + '-2')) {
      if (document.getElementById('edit-category-' + i + '-2').selectedIndex != -1)
        tid = document.getElementById('edit-category-' + i + '-2').options[document.getElementById('edit-category-' + i + '-2').selectedIndex].value;
    }
    $.create('input', {
      'type': 'hidden',
      'id': 'edit-category-field' + i,
      'name': 'category-' + i,
      'value': tid,
      'style': 'display:none;'
    }).appendTo('.body-field-wrapper');
    if (tid && !$('#edit-field-primary-0-value').val()) {
      $('#edit-field-primary-0-value').val(tid)
    }
  }
}

function buildCategoriesEditElementsForTip(categories){
  if (categories instanceof Array) {
    for (var i = 0; i < categories.length; i++) {
      createRootCategoriesSelector(cats);
      var id = selector_id;
      document.getElementById(categories[i][categories[i].length - 1].tid + '-' + id).selected = true;
      if (categories[i].length == 3) {
        createFirstLevelCategories(document.getElementById('edit-category-' + id).selectedIndex, id);
        document.getElementById(categories[i][1].tid + '-' + id).selected = true;
        createSecondLevelCategories(document.getElementById('edit-category-' + id + '-1').selectedIndex, id);
        document.getElementById(categories[i][0].tid + '-' + id).selected = true;
      }
      if (categories[i].length == 2) {
        createFirstLevelCategories(document.getElementById('edit-category-' + id).selectedIndex, id);
        document.getElementById(categories[i][0].tid + '-' + id).selected = true;
      }
    }
  }
}

function htmlspecialchars(text){
  var chars = Array("&", "<", ">", '"', "'");
  var replacements = Array("&amp;", "&lt;", "&gt;", "&quot;", "'");
  for (var i = 0; i < chars.length; i++) {
    var re = new RegExp(chars[i], "gi");
    if (re.test(text)) {
      text = text.replace(re, replacements[i]);
    }
  }
  return text;
}

function get_visible_image(){
  var image = $('.images:visible').attr('id');
  if (!image)
    return false
  image = image.split('-');
  return image[2];
}

function browse_image_next(id){
  if (!id)
    return false
  var images = [];
  $('.images:hidden').each(function(){
    images.push(this.id);
  });
  for (var i = 0; i < images.length; i++) {
    var image = images[i].split('-');
    if (parseInt(image[2]) > parseInt(id)) {
      $('div.images').hide();
      $('div#' + images[i]).show();
      $('input#edit-new-pid').val(get_visible_image());
      var subject = $('#image-wrapper-' + image[2] + ' h3').text();
      $('#edit-subject').val(subject);
      return false;
    }
  }
}

function browse_image_prev(id){
  if (!id)
    return false
  var images = [];
  $('.images:hidden').each(function(){
    images.push(this.id);
  });
  for (var i = 0; i < images.length; i++) {
    var image = images[i].split('-');
    if (parseInt(image[2]) < parseInt(id)) {
      $('div.images').hide();
      $('div#' + images[i]).show();
      var subject = $('#image-wrapper-' + image[2] + ' h3').text();
      $('#edit-subject').val(subject);
//      $('form#forward-form').attr('action', '/forward?path=node/' + image[2]);
    }
  }
  $('input#edit-new-pid').val(get_visible_image());
  return false;
}

function manageStatesChoosing(){
  var country = $('#edit-field-therapist-contact-0-country').selectedValues();
  if (country[0] == 'ca' || country[0] == 'us') {
    if (country[0] == 'ca') {
      var provinces = {
        'none': 'Please select',
        'on': 'ON',
        'qc': 'QC',
        'ns': 'NS',
        'nb': 'NB',
        'mb': 'MB',
        'bc': 'BC',
        'pe': 'PE',
        'sk': 'SK',
        'ab': 'AB',
        'nl': 'NL'
      };
    }
    else if (country[0] == 'us') {
      var provinces = {
        'none': 'Please select',
        'al': 'AL',
        'ak': 'AK',
        'az': 'AZ',
        'ar': 'AR',
        'ca': 'CA',
        'co': 'CO',
        'ct': 'CT',
        'de': 'DE',
        'dc': 'DC',
        'fl': 'FL',
        'ga': 'GA',
        'hi': 'HI',
        'id': 'ID',
        'il': 'IL',
        'in': 'IN',
        'ia': 'IA',
        'ks': 'KS',
        'ky': 'KY',
        'la': 'LA',
        'me': 'ME',
        'md': 'MD',
        'ma': 'MA',
        'mi': 'MI',
        'mn': 'MN',
        'ms': 'MS',
        'mo': 'MO',
        'mt': 'MT',
        'ne': 'NE',
        'nv': 'NV',
        'nh': 'NH',
        'nj': 'NJ',
        'nm': 'NM',
        'ny': 'NY',
        'nc': 'NC',
        'nd': 'ND',
        'oh': 'OH',
        'ok': 'OK',
        'or': 'OR',
        'pa': 'PA',
        'ri': 'RI',
        'sc': 'SC',
        'sd': 'SD',
        'tn': 'TN',
        'tx': 'TX',
        'ut': 'UT',
        'vt': 'VT',
        'va': 'VA',
        'wa': 'WA',
        'wv': 'WV',
        'wi': 'WI',
        'wy': 'WY',
        'as': 'AS',
        'gu': 'GU',
        'mp': 'MP',
        'pr': 'PR',
        'vi': 'VI',
        'fm': 'FM',
        'mh': 'MH',
        'pw': 'PW',
        'aa': 'AA',
        'ae': 'AE',
        'ap': 'AP',
        'cz': 'CZ',
        'pi': 'PI',
        'tt': 'TT',
        'cm': 'CM'
      };
    }
    $('input#edit-field-therapist-contact-0-province').hide();
    $('input#edit-field-therapist-contact-0-province').css('width', '1%');
    if ($('select#edit-field-therapist-contact-0-province-select').length == 0) {
      $.create('select', {
        'id': 'edit-field-therapist-contact-0-province-select'
      }).appendTo('div#edit-field-therapist-contact-0-province-wrapper');
    }
    else {
      $('select#edit-field-therapist-contact-0-province-select').show();
      $('select#edit-field-therapist-contact-0-province-select').removeOption(/./);
    }
    $('#edit-field-therapist-contact-0-province-select').attr('name', 'field_therapist_contact[0][province]');
    $('#edit-field-therapist-contact-0-province').attr('name', 'province');
    $('select#edit-field-therapist-contact-0-province-select').css('width', '54%');
    $('select#edit-field-therapist-contact-0-province-select').addOption(provinces);
    $('select#edit-field-therapist-contact-0-province-select').selectOptions('none');
  }
  else {
    $('#edit-field-therapist-contact-0-province').attr('name', 'field_therapist_contact[0][province]');
    $('#edit-field-therapist-contact-0-province-select').attr('name', 'province');
    if ($('select#edit-field-therapist-contact-0-province-select').length > 0) {
      $('input#edit-field-therapist-contact-0-province').css('width', '53%');
      $('select#edit-field-therapist-contact-0-province-select').css('width', '1%');
      $('select#edit-field-therapist-contact-0-province-select').hide();
      $('input#edit-field-therapist-contact-0-province').show();
    }
  }
}

function createRelatedTipsSearchForm(){
  $('div#help-balloon-content').hide();
  $.create('form', {
    'action': '/post/sextip',
    'method': 'post',
    'class': 'search-related-tip-form'
  }).appendTo("#edit-field-favourite-value-wrapper");
  $.create('label', {
    'for': 'edit-search-titles'
  }, "Find related tips for 'You May Also Want to Read' section").appendTo(".search-related-tip-form");
  $.create('div', {
    'class': 'description sextip-new-description'
  }, "The search will bring up a list of previously published tips relating to your search term. Select any tips that will be linked to the tip currently being written or edited, then click \"Add selected\"").appendTo(".search-related-tip-form");

$.create('div', {
  'class': 'field-search'
   }).appendTo(".search-related-tip-form");

  $.create('label', {
    'for': 'edit-search-titles'
  }, 'Containing all of the words:').appendTo(".field-search");
$.create('label', {
    'for': 'edit-search-phrase'
  }, 'Containing the phrase:').appendTo(".field-search");
  $.create('label', {
    'for': 'edit-search-none-contain'

  }, 'Containing none of the words:').appendTo(".field-search");


  $.create('input', {
    'id': 'edit-search-titles',
    'type': 'text',
    'name': 'titles',
    'maxlength': '120'
  }).appendTo(".search-related-tip-form");

  

   $.create('input', {
    'id': 'edit-search-phrase',
    'type': 'text',
    'name': 'phrase',
    'maxlength': '120'
  }).appendTo(".search-related-tip-form");



  $.create('input', {
    'id': 'edit-search-none-contain',
    'type': 'text',
    'name': 'none-contain',
    'maxlength': '120'
  }).appendTo(".search-related-tip-form");

  $.create('input', {
    'id': 'edit-search-submit',
    'type': 'submit',
    'name': 'op',
    'value': 'Search'
  }).appendTo(".search-related-tip-form");

  $.create('div', {
    'id': 'related-tips-titles-wrapper'
  }).appendTo(".search-related-tip-form");
  $("form.search-related-tip-form").submit(function(){
    if ($("#edit-search-titles").val() || $("#edit-search-phrase").val() || $("#edit-search-none-contain").val()) {
      ajaxSearchRelatedTips($("#edit-search-titles").val(), $("#edit-search-phrase").val(), $("#edit-search-none-contain").val(), 0);
    }
    return false;
  });
}

function ajaxSearchRelatedTips(title, phrase, non_contein, page){
  $("form.search-related-tip-form").css('cursor', 'wait');
  if(page >= 1) {
    page = "?page=" + page;
  } else {
    page = '';
  }
  $.ajax({
    type: "POST",
    url: "/search/related/tips" + page,
    data: "keywords=" + title + "&id=" + window.location.pathname.split('/')[2] + "&phrase=" + phrase + "&non_contein=" + non_contein,
    success: function(html){
      if (!$("div.related-tips-wrapper")[0])
        $.create('div', {
          'class': 'related-tips-wrapper'
        }).appendTo("div#related-tips-titles-wrapper");
      $('div.related-tips-wrapper').html(html);
      $("form.search-related-tip-form").css('cursor', 'default');
      ajaxSearchRelatedTipsPager();
    }
  });
}
function strpos(haystack, needle, offset){	
	var i = haystack.indexOf( needle, offset ); 
	return i >= 0 ? i : false;
}

function ajaxSearchRelatedTipsPager() {
  $('#add-related-tip-form .pager a.active').click(function() {
    href_link = $(this).attr("href");
    start_pos = strpos(href_link, 'page=');
    if(start_pos) {
      page = href_link.substr(start_pos + 5, strpos(href_link, '&', start_pos) - start_pos - 5)
    } else {
      page = '';
    }
    ajaxSearchRelatedTips($("#edit-search-titles").val(), $("#edit-search-phrase").val(), $("#edit-search-none-contain").val(), page);
    return false;
  });
}
function ajaxAddSelectedToRelatedCategory(){
  var related = new Array;
  $("input.edit-related-sextip").each(function(){
    if ($(this).attr('checked')) {
      var id = $(this).attr('id').split("-")[1];
      related.push(id);
    }
    this.checked = false
  });
  if ($("input#edit-field-related-tips-0-value").val() == '') {
    $("input#edit-field-related-tips-0-value").val(related.join(","));
  }
  else {
    $("input#edit-field-related-tips-0-value").val($("input#edit-field-related-tips-0-value").val() + ',' + related.join(","));
  }
  $("form#add-related-tip-form").css('cursor', 'wait');
  $.ajax({
    type: "POST",
    url: "/search/related/tips",
    data: "related=" + $("input#edit-field-related-tips-0-value").val(),
    success: function(html){
      if (!$("div.selected-related-tips-wrapper")[0])
        $.create('div', {
          'class': 'selected-related-tips-wrapper'
        }).appendTo("div#related-tips-titles-wrapper");
      $('div.selected-related-tips-wrapper').html(html);
      $("form#add-related-tip-form").css('cursor', 'default');
    }
  });
}

function deleteCategory (id){
  id = id.split("-")[1];
  var val = $("input#edit-field-related-tips-0-value").val();
  var id2 = id + ",";
  $("input#edit-field-related-tips-0-value").val(val.replace(id2, ""));
  var val = $("input#edit-field-related-tips-0-value").val();
  $("input#edit-field-related-tips-0-value").val(val.replace(id, ""));
  var val = $("input#edit-field-related-tips-0-value").val();
  if (val.substr(val.length - 1) == ',') $("input#edit-field-related-tips-0-value").val(val.substr(0, val.length - 1));
  $("form#add-related-tip-form").css('cursor', 'wait');
  $.ajax({
    type: "POST",
    url: "/search/related/tips",
    data: "related=" + $("input#edit-field-related-tips-0-value").val() + "&delete=true",
    success: function(html){
      if (!$("div.selected-related-tips-wrapper")[0])
        $.create('div', {
          'class': 'selected-related-tips-wrapper'
        }).appendTo("div#related-tips-titles-wrapper");
      $('div.selected-related-tips-wrapper').html(html);
      $("form#add-related-tip-form").css('cursor', 'default');
    }
  });
}
var ection = 0;
$(function() {
  var url_href = location.href;
  url_href = url_href.indexOf('forward?path=node');
  if(url_href + 1) {
    $('#edit-include-comments').change(function(){
      if($('#edit-include-comments').attr('checked')) {
        ection = 1;
      } else {
        ection = 0;
        /*ection = $('#edit-preview').attr('onclick');
        //ection.replace('?preview=1&comments=1', '?preview=1');
        $('#edit-preview').attr('onclick', ection);
        alert(ection);*/
      }
    });
  }
});
$(function(){
  document.body.onmousemove = function(){
    for (var i = 0; i < $('.error ul li').length; i++) {
      if ($('.error ul li').eq(i).html().indexOf("Please enter text") != -1)
        var cont_error = 'border: 1px solid red'
    }
    if (cont_error)
      document.getElementById("edit-body_tbl").style.border = "1px solid red"
    document.body.onmousemove = null
  }
  for (var i = 0; i < $('.error ul li').length; i++) {
    if ($('.error ul li').eq(i).html().indexOf("Primary Category") != -1)
      var prim_cat_error = 'border: 1px solid red;'
  }
  if (!prim_cat_error) {
    var prim_cat_error = '';
  }
  $selwdth = $('#edit-category-1').width() + 4
  $('#categor-wrapper-1').css({
    'width': $selwdth
  })
  if (prim_cat_error) {
    $('#categor-wrapper-1').css({
      'border': '1px solid red'
    })
  }
})

$(function(){
  if ($('#edit-filedescr-wrapper > label > span.form-required').html()) var required_yet = true
  else var required_yet = false
  $('#edit-upload').bind('change', function() {
    if ($('#filename-deletion-wraper').html() && $('#filename-deletion-wraper').html().length > 20) {
      if (!required_yet) {
        $('#edit-filedescr-wrapper > label').html($('#edit-filedescr-wrapper > label').html() +  '<span class=\'form-required\' title=\'This field is required.\'>*</span>')
        required_yet = true
      }
    }
    else {
      if (this.value && !required_yet) {
        $('#edit-filedescr-wrapper > label').html($('#edit-filedescr-wrapper > label').html() +  '<span class=\'form-required\' title=\'This field is required.\'>*</span>')
          required_yet = true
      }
      else if (!this.value) {
        $('#edit-filedescr-wrapper > label').html('Describe the image in detail:');
          required_yet = false
      }
    }
  })
})
  
$(function(){
  if (window.location.pathname!= '/reg') return false
  registration_agree_error = (typeof registration_agree_error != 'undefined') ? registration_agree_error : false
  registration_specialty_error = (typeof registration_specialty_error != 'undefined') ? registration_specialty_error : false
  registration_experience_error_1 = (typeof registration_experience_error_1 != 'undefined') ? registration_experience_error_1 : false
  registration_experience_error_2 = (typeof registration_experience_error_2 != 'undefined') ? registration_experience_error_2 : false
  registration_experience_error_3 = (typeof registration_experience_error_3 != 'undefined') ? registration_experience_error_3 : false
  registration_experience_error_4 = (typeof registration_experience_error_4 != 'undefined') ? registration_experience_error_4 : false
  registration_therapy_error = (typeof registration_therapy_error != 'undefined') ? registration_therapy_error : false
  registration_state_error = (typeof registration_state_error != 'undefined') ? registration_state_error : false
  if (registration_agree_error) {
    if (!$.browser.msie)
      $('#edit-agree').wrap('<span style="border: 1px solid red; padding: 1px"></span>')
  }
  if (registration_specialty_error) {
    $('#edit-field-speciality-value').css({'border': '1px solid red'})
  }
  if (registration_experience_error_1) {
    $('#edit-field-general-expirience-y-value').css({'border': '1px solid red'})
  }
  if (registration_experience_error_2) {
    $('#edit-field-general-expirience-m-value').css({'border': '1px solid red'})
  }
  if (registration_experience_error_3) {
    $('#edit-field-sex-therapy-y-value').css({'border': '1px solid red'})
  }
  if (registration_experience_error_4) {
    $('#edit-field-sex-therapy-m-value').css({'border': '1px solid red'})
  }
  if (registration_therapy_error) {
    $('#edit-field-sex-therapy-0-value-date').css({'border': '1px solid red'})
  }
  if (registration_state_error) {
    $('#edit-field-therapist-contact-0-province-select').css({'border': '1px solid red'})
  }
})

/*
 * Function to add sliding capabilities to the divs
 * To add this functionality, you need to add the class 'sliding' to the div
 * Default min height - 42px, you may change it in css
 * The target element can not have nested elements
 */
$(function(){
  var maxStrLength = 250 // max text length in minimized state
  $('.sliding').each(function(index) {
    if (this.childNodes[0].nodeValue.length > maxStrLength) {
      $(this).css({'border-right': '1px solid #EBEBEB', 'padding-right': '20px'})
      var fullText = this.childNodes[0].nodeValue // save full text to restore in future
      this.childNodes[0].nodeValue = text_length(this.childNodes[0].nodeValue, maxStrLength)
      $(this).css({'height': 'auto'})
      /* Add a button to control the state of the element and the appointment of its event handlers */
      $('<div class="slidDownIcon" onclick="return false" title="Read more">+</div>').appendTo(this).bind('click', function() {
        if (this.childNodes[0].nodeValue == '+') {
          $(this).attr({'title': 'Close'})
          this.childNodes[0].nodeValue = '-'
          this.parentNode.childNodes[0].nodeValue = fullText
          $(this).parent().css({'height': 'auto', 'overflow': 'visible'})
          $(this).css({'line-height': '9px', 'padding': '0 0 0 3px'})
        }
        else {
          $(this).attr({'title': 'Read more'})
          this.parentNode.childNodes[0].nodeValue = text_length(this.parentNode.childNodes[0].nodeValue, maxStrLength)
          this.childNodes[0].nodeValue = '+'
          $(this).parent().css({'overflow': 'hidden'})
          $(this).css({'line-height': '11px', 'padding': '0 2px'})
        }
      })
    }
    else {
      $(this).css({'height': 'auto', 'overflow': 'visible'})
    }
  })
})
  
/*
 * Function to change the width of the elements with the class of 'sliding' when resizing the screen on the profile page.
 */
  
$(function(){
  if (location.href.indexOf('directory') != -1) {
    var newWidth = 0
    $('.sliding').each(function(){
      newWidth = $(window).width()/2 - 170
      $(this).css({'width': newWidth})
    })
    $(window).bind('resize', function() {
      $('.sliding').each(function(){
        newWidth = $(window).width()/2 - 170
        $(this).css({'width': newWidth})
      })
    })
  }
})
  
 /* Text lenth limit
 *
 * @param content - some content
 * @param limit - count of chars
 * @return string
 */
function text_length(content, limit) {
  if (content.length > limit) content = content.substr(0, content.substr(0, limit).lastIndexOf(' ')) + '...';
  return content;
}

function philosophy_handler (obj, id, op) {
  if (op == 'more') {
    var parent = obj.parentNode
    if (id.substr(0, 10) == 'philosophy') {
      parent.innerHTML = eval(id) + "<a href='javascript: void(0)' onclick='philosophy_handler(this, \"" + id + "\", \"hide\")'> [hide]</a>"
    }
  }
  else if (op == 'hide') {
    var parent = obj.parentNode
    if (id.substr(0, 10) == 'philosophy') {
      parent.innerHTML = text_length(eval(id),256) + "<a href='javascript: void(0)' onclick='philosophy_handler(this, \"" + id + "\", \"more\")'> [more]</a>"
    }
  }
}

