﻿if(typeof(DT) == "undefined"){ DT = {}};

DT.notification = function(){
  return {
      options : { 
                  seconds_to_display: 5,
                  slide_rate : "slow",
                  default_css : "default"
                },
      showing : false,
      messages : [],
      instances : 0,
      interval_id : null,
      init : function(){
        var element = $("<div id='dt-notifier'><div id='dt-message' /></div")
            .appendTo(document.body);

        this.element = element;
        this.input = $(element).find("#dt-message");
        this.input.addClass(this.options.default_css);
      },
      add : function(msg){
        this.messages.push(msg); 
      },
      display_success : function(){
        this.input
            .removeClass(this.options.default_css)
            .addClass("success");
        
        for(var i in this.messages){
          this.show(this.messages[i], 8);
        }
      },
      note : function(msg,seconds){
        $(this.input).addClass("note");

        this.show(msg,seconds);
      },
      alert : function(msg,seconds){
        $(this.input).addClass("alert");
        this.show(msg,seconds);
      },
      get_time_to_display : function(ms){
        var seconds = ms || this.options.seconds_to_display;
        return seconds * 1000;
      },
      hide : function(){
        this.showing=false;
        $(this.input).removeClass("alert note");
        $(this.element).slideUp(this.options.slide_rate);
      },
      should_hide : function(){
        this.instances--;

        if(this.instances <= 0){
          this.instances=0;
          return true;
        }

        return false;
      },
      show : function(msg,seconds){
        this.instances++;
        $(this.input).text(msg);

        this.showing=true;

        $(this.element).slideDown(this.options.slide_rate);

        this.interval_id = setTimeout(function(){
            if(!DT.notification.should_hide()) return;

            DT.notification.hide();
          },this.get_time_to_display(seconds));
      }
  }
}();


// Force namespace qualification on global functions (e.g., $.dovetail.messageBox)
$.extend({
    dovetail: {
        applyAlternateItemStyles: function (element) {
            $('.section-content > .history-item > .history-item-header:even', element).each(function () { $(this).addClass('header-gray'); });
            $('.section-content > .history-item > .history-item-header:odd', element).each(function () { $(this).addClass('header-blue'); });
        }
    }
});

$(document).ready(function () {
    DT.notification.init();

    $('form.validate').validate({
        errorPlacement: function (error, element) {
            error.appendTo(element.parent());
        },
        onfocusout: false,
        errorContainer: "#Client-Errors",
        errorLabelContainer: "#Client-Errors ul",
        wrapper: "li",
        invalidHandler: function () {
            $('#Server-Errors').hide();
        },
        messages : {
          Email : {
            email : function(rule,element){
              return "'" + $(element).val() + "' is an invalid email address.";
            }
          }
        }
    });

    // add UI to required elements except to login form
    $("form.validate:not('#LoginForm') .required").each(function(i,el){
        $(el).parent().append("<em class='required-indicator'>*</em>");
    });

    var searches = $('.entity-search');
    if (searches.size() != 0) {
        searches.entitySearch(); 
    }

    if ($('#Server-Errors').size() != 0) {
        var errors = $('#Server-Errors').metadata({ type: 'elem', name: 'script' }).errors;
        $.each(errors, function (index, error) {
            var input = $('#' + error.ElementId);
            input.addClass('error');

            $('<span class="error">' + error.Message + '</span>').appendTo(input.parent());
            input.focus();
        });

        //setTimeout(function () { $('#Server-Errors').fadeOut(); }, 3000);
    }

    var $success = $('.success');
    if ($success.size() != 0) {
      //setTimeout(function () { $success.fadeOut(); }, 5000);
    }

    $('form .limit').each(function(i,el){
      var $text = $(this);
      var max = $text.attr("maxlength");

      if(max=='undefined') return;

      var countdown = "<span class='countdown' />";
      $text.parent().append(countdown);

      var first = null;
      $text.bind("keyup",function(e){
        var go = function(element,val){
          $(element).siblings(".countdown").html(val + " characters left");
        };

        if(first === null) go(this,max);
        first = true;

        var left = max - $(this).val().length;

        if(left < 0){ this.value = this.value.substring(0,max); }

        go(this,left);
      });
    });

});

$.widget('ui.dovetailDropDown', {
    options: {
    },
    _create: function () {
        var self = this;
        var element = $(this.element);
        var hiddenElement = $(self.options.hiddenElement);
        hiddenElement.val($('#' + element.attr('id') + ' option:selected').val());

        element.bind("change", function () {
            hiddenElement.val($('option:selected', this).val());
        });
    },
    destroy: function () {
        $.Widget.prototype.destroy.apply(this, arguments);
    }
});

