function isDefined(variable) {
    return variable !== undefined;
}

function isNull(variable) {
    return (variable === null);
}

function toFixed(number, precision) {
    var power = Math.pow(10, precision || 0);
    return String(Math.round(number * power)/power);
}

/*! Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */

(function($) {

  // Returns whether or not a result set has results in it
  $.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
  };

  // http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
  // checks if a element exists
  $.fn.exists = function(){return jQuery(this).length>0;};
})(jQuery);

function twttrAsyncInit() {
  $(document).trigger("twttr.ready");
}

$(function() {

  /* animation magic */
  $('.js-hide-on-init').hide();

  /*
   * reuseable ajax-form helper for simple forms
   * usage: <div class="ajax-container">
   *          <form action="/target" method="post" class="ajax-form">
   *
   */
  $('.ajax-form').live('submit', function() {
    var formData = $(this).serialize();
    var me = $(this);
    $(this).find(".spinner").show();

    $.post($(this).attr('action'), formData, function(data) {
      if(data == "status-done") {
        if(typeof(gRedirectPath) != 'undefined') {
          window.location = gRedirectPath;
        } else {
          window.location.reload();
        }
      } else {
        me.closest(".ajax-container").html(data);
        me.find(".spinner").show();
      }
    });
    return false;
  });

  $('.flash_message .close').click( function(e) {
    e.preventDefault();
    $(this).parent().slideUp();
  });

  $('.notification-box .close').click( function(e) {
     e.preventDefault();
     $(this).parent().parent().slideUp();
   });

  if ($(".garmz-dialog").exists()) {
    $(".garmz-dialog").dialog({
      autoOpen: false,
      modal: true,
      draggable: false,
      resizable: false,
      width: 615,
      dialogClass: 'common-dialog'
    });
  }

  $('.common-dialog-closex').click(function(e) {
    $(this).closest('.garmz-dialog').dialog('close');
    return false;
  });

  /*
   * reuseable dialog trigger
   * usage: <a href="#login-dialog" class="dialog-trigger>
   *        <div id="login-dialog" class="garmz-dialog">
   *
   */
  $('a.dialog-trigger').live("click", function (e) {

    e.preventDefault();

    $(".garmz-dialog").dialog('close');

    var el = $($(this).attr('href'));
    el.dialog('open');
    $(".ui-dialog-titlebar").hide();

    if (el.find("form").exists() && el.find("form input[type!=hidden]").exists()) {
      el.find("form input[type!=hidden]").first().focus();
    }
    var isIE7 = $.browser.msie && $.browser.version == "7.0";// sorry, no other way to detect that. see http://forum.jquery.com/topic/dialog-position-issue
    if (isIE7) {
    $.scrollTo(el);
    }
  });

  /* todo: we could redo that as well with classes
   *        e.g. class="truncate characters-180"
   */
  // Truncation of texts
  if ($(".label-box").exists()) {
    $(".label-box p").truncate(
      { max_length: 100, more: "+&nbsp;More", less: "-&nbsp;Less", linkClass: "toggleDesc" }
    );
  }

  if ($(".design-info").exists()) {
    $(".design-info .styletags").truncate(
      { max_length: 50, more: "+&nbsp;More", less: "-&nbsp;Less", linkClass: "toggleDesc" }
    );
    $(".design-info .fabrics-and-colors-desc").truncate(
      { max_length: 180, more: "+&nbsp;More", less: "-&nbsp;Less", linkClass: "toggleDesc" }
    );
  }

  /*
   * reuseable truncate trigger
   * usage: <p class="truncate-180"> text.... </p>
   */
  if ($(".truncate-180").exists()) {
    $(".truncate-180").truncate(
      { max_length: 180, more: "+&nbsp;More", less: "-&nbsp;Less", linkClass: "toggleDesc" }
    );
  }

  /*
   * reuseable show-trigger
   * usage: <a name="change-password" class="show-trigger">toggle</a>
   *        <div class="change-password js-hide-on-init">show me</div>
   */
  $('a.show-trigger').click(function (e) {
    e.preventDefault();
    var el = $("." + $(this).attr('name'));
    el.toggle();
    if (el.find("form").exists() && el.find("form input[type!=hidden]").exists()) {
      el.find("form input[type!=hidden]").first().focus();
    }
  });


  /*
   * reuseable show-trigger for hints
   * usage: <textarea class="hint-trigger"></textarea>
   *        <p class="hint">hint text</p>
   * note: relys on the fact that the hint comes next to the element
   */

  $(".hint").hide();
  $(".hint-trigger").live("focus", function (e) {
    // we need to give the hint the same margin-top value as the textareas
    //  otherwise its floating to high

    var margin_fix = $(this).css("marginTop");

    // if we are inclosed in a fieldWithErrors we have to search for the hint differently
    if ($(this).parent().hasClass("fieldWithErrors")) {
      $(this).parent().next(".hint").css("marginTop", margin_fix).show();
    }
    else {
      $(this).next(".hint").css("marginTop", margin_fix).show();
    }
  });

  $(".hint-trigger").live("blur", function (e) {

    if ($(this).parent().hasClass("fieldWithErrors")) {
      $(this).parent().next(".hint").hide();
    }
    else {
      $(this).next(".hint").hide();
    }
  });


  /*
   * reuseable clipboard box
   * usage: <div id="clipboard-box">
   *          <input type="text" id="clipboard-content" readonly="readonly"
   *      value="http://www.garmz.com/milluela/cariblue" class="autoselect" />
   *          <div id="clipboard-trigger-box">
   *            <a href="#" id="clipboard-trigger">
   *              <img src="/images/copy-to-clipboard.png"
   *                   alt="copy to clipboard" />
   *              </a>
   *           </div>
   *           <div class="clear"></div>
   *        </div>
   *
   */
  var clip = null;
  if ($('#clipboard-box').exists()) {
    ZeroClipboard.setMoviePath( '/javascripts/lib/zeroclipboard/ZeroClipboard.swf' );
    clip = new ZeroClipboard.Client();
    clip.setHandCursor( true );

    clip.addEventListener('load', function (client) {
      clip.setText( $('#clipboard-content').val() );
    });

    clip.glue( 'clipboard-trigger', 'clipboard-box' );
  }



  /*
   * simulating a.action-button behaviour for input elements
   */
  $('input.submit-button').live('hover', function (e) {
      $(this).toggleClass('submit-button-hover');
  }).click(function (e) {
    $(this).toggleClass('submit-button-active');
  });


  /*
   * reuseable trigger for other fields next to select boxes
   * usage: <select class="other-trigger" id="design_category">
   *        <input class="other" id="design_category_other" type="text" class="text" value="" />
   * note: relys on the correct id namings by rails
   */

  $(".other-trigger").each(function(i) {
    var other_field = "#"+ $(this).attr('id') +"_other";
    if($(this).val() != "other") {
      $(other_field).hide();
    }

    /// if other-trigger has an form error we pass the class to the other-field
    // to be able to provide better ux
    // use trigger-field-with-error if you need styling
    if ($(this).hasClass("field-with-error")) {
      $(other_field).addClass("field-with-error");
      $(this).addClass("trigger-field-with-error").removeClass("field-with-error");
    }
  });

  $(".other-trigger").change( function (e) {
    var other_field = "#"+ $(this).attr('id') +"_other";

    if($(this).val() == "other"){
      $(other_field).show();
      $(other_field).focus();
    }else{
      $(other_field).val('');
      $(other_field).hide();
    }
  });


  /*
   * reusable trigger
   * usage: <input class="radio-other-trigger" id="design_fit_other" type="radio" value="other" />
   *        <input class="radio-other" id="design_fit_other_input" type="text" value="Other..." />
   * note: relys on the correct id namings by rails
   */
  $('.radio-other-trigger').each( function (i) {

    // if you click on the radio button your keyboard focus moves to the input field
    $(this).click( function(e) {
      $(this).next("input[type=text]").focus();
    });

    /// if radio-other-trigger has an form error we pass the class to the other-field
    // to have a better ux
    // use trigger-field-with-error if you need styling
    if ($(this).hasClass("radio-field-with-error")) {
      $(this).next("input[type=text]").addClass("field-with-error");
      $(this).addClass('trigger-field-with-error').removeClass("radio-field-with-error");
    }
  });

  // part two of the radio-other trigger
  // if a user clicks on the other-field we select the radio button as well
  $('.radio-other').focus( function(e) {
      $(this).prev("input[type=radio]").attr("checked", "checked");
  });

  /*
   * resuseable input field clearer
   * usage: <input type="text" class="text clearme" value="default text" />
   */

  $('.clearme').live("focus", function() {
    $(this).val("");
    $(this).removeClass("clearme");
  });

  /*
   * reuseable autoselecter
   * usage: <input type="text" value="abcdef" class="text autoselect" />
   */
  $('input.autoselect').focus(function() {
   $(this).select();
  });
  /*
   * reuseable image replacer
   * usage: <img src="/images/design_sample_big1.jpg" class="browsing-image image-replace-container" />
   * <div class="image-replace-thumbnails clearfix">
   *  <a href="#" class="image-replace-trigger active" name="design_sample_big1.jpg">
   *     <img src="/_html/testdata/design_sample_small1.jpg" alt="next Design Image" />
   *  </a>
   * </div>
   *
   */
  $('.image-replace-trigger').live('click', function (e) {
      e.preventDefault();

      if ($(this).hasClass("active")) {
        return;
      }

      var display_image = $("." + $(this).attr("rel"));
      var href = $(this).attr('href');
      display_image.fadeOut(100, function() { $(this).load(href, function() { $(this).fadeIn(100); });  });
      $(this).siblings('.image-replace-trigger').removeClass("active");
      $(this).addClass("active");
  });

  $(".public-heart-vote").live('click', function() {
    var votePath = $(this).attr("href");
    gRedirectPath = votePath;
    $("#login-link").click();
    return false;
  });

  $(".hide-email-request").click(function() {
    var path = $(this).attr("href");
    $.post(path, 'text');
    return false;
  });

  $("#add-email-link").click(function() {
      alert("add email di");
    $("#add-email-dialog").show();
    return false;
  });

}); // doc ready
