
$(document).ready(function(){
  Sexy.initialize();
});

jQuery.bind = function(object, method){
  var args = Array.prototype.slice.call(arguments, 2);  
  return function() {
    var args2 = [this].concat(args, $.makeArray( arguments ));  
    return method.apply(object, args2);  
  };  
};  

jQuery.fn.delay = function(time,func){
	return this.each(function(){
		setTimeout(func,time);
	});
};


jQuery.fn.extend({
  $chain : [],
  chain: function(fn) {
    this.$chain.push(fn);
    return this;
  },
  callChain: function(context) {
    return (this.$chain.length) ? this.$chain.pop().apply(context, arguments) : false;
  },
  clearChain: function(){
    this.$chain.empty();
    return this;
  }
});

(function($) {

  Sexy = {
    getOptions: function() {
      return {
        name            : 'SexyAlertBox',
        zIndex          : 65555,
        onReturn        : false,
        onReturnFunction: function(e) {},
		onOpenFunction  : function(e) {},
        BoxStyles       : { 'width': 385 },
        OverlayStyles   : { 'backgroundColor': '#111', 'opacity': 0.7 },
        showDuration    : 300,
        closeDuration   : 200,
        moveDuration    : 500,
        onCloseComplete : $.bind(this, function() {
          this.options.onReturnFunction(this.options.onReturn);
        }),
		onOpenComplete  : $.bind(this, function() {
          this.options.onOpenFunction(this.options.onOpen);
        })
      };
    },


    initialize: function(options) {
      this.i=0;
      this.options = $.extend(this.getOptions(), options);
			//$('body').append('<div id="BoxOverlay"></div><div id="'+this.options.name+'-Box"><div id="'+this.options.name+'-InBox"><div id="'+this.options.name+'-BoxContent"><div id="'+this.options.name+'-BoxContenedor"></div></div></div></div>');
			$('body').append('<div id="BoxOverlay"></div>');
			$('#BoxOverlay').css({
        position        : 'absolute',
        top             : 0,
        left            : 0,
				opacity         : this.options.OverlayStyles.opacity,
				backgroundColor : this.options.OverlayStyles.backgroundColor,
				'z-index'       : this.options.zIndex,
        height          : $(document).height()+180,
				width           : $(document).width()
			}).hide();
			
			$('body').append('<div id="'+this.options.name+'-Box"><div id="'+this.options.name+'-InBox"><div id="'+this.options.name+'-BoxContent"><div id="'+this.options.name+'-BoxContenedor"></div></div></div></div>');
			this.Content    = $('#'+this.options.name+'-BoxContenedor');
			this.Contenedor = $('#'+this.options.name+'-BoxContent');
			this.InBox      = $('#'+this.options.name+'-InBox');
			this.Box        = $('#'+this.options.name+'-Box');
			
			
			
			this.Box.css({
        display         : 'none',
        position        : 'absolute',
        top             : 0,
        left            : 0,
				'z-index'       : this.options.zIndex + 2,
				width           : this.options.BoxStyles.width + 'px'
			});

      this.preloadImages();

      $(window).bind('resize', $.bind(this, function(){
        if(this.options.display == 1) {
          $('#BoxOverlay').css({
            height          : 0,
            width           : 0
          });
          $('#BoxOverlay').css({
            height          : $(document).height(),
            width           : $(document).width()
          });
          this.replaceBox();
        }
      }));

      this.Box.bind('keydown', $.bind(this, function(obj, event){
        if (event.keyCode == 27){
          this.options.onReturn = false;
          this.display(0);
        }      
      }));

      $(window).bind('scroll', $.bind(this, function(){
        this.replaceBox();
      }));
			
    },

    replaceBox: function() {
      if(this.options.display == 1) {
        
        this.Box.stop();
        
        this.Box.animate({
          left  : ( ($(document).width() - this.options.BoxStyles.width) / 2),
          top   : ( $(document).scrollTop() + ($(window).height() - this.Box.outerHeight()) / 2 )
        }, {
          duration  : this.options.moveDuration,
          easing    : 'easeOutBack'
        });

        $(this).delay(this.options.moveDuration, $.bind(this, function() {
          $('#BoxAlertBtnOk').focus();
          $('#BoxPromptInput').focus();
          $('#BoxConfirmBtnOk').focus();
		  
        }));
      }
    },

    display: function(option) {
      if(this.options.display == 0 && option != 0 || option == 1) {

	   /*
        if (!$.support.maxHeight) { //IE6
          $('embed, object, select').css({ 'visibility' : 'hidden' });
        }
		 */

        this.togFlashObjects('hidden');

        this.options.display = 1;


        $('#BoxOverlay').stop();
		//$('#BoxOverlay').show(); return;
        $('#BoxOverlay').fadeIn(this.options.showDuration, $.bind(this, function(){
		  
          this.Box.css({
            display         : 'block',
            left            : ( ($(document).width() - this.options.BoxStyles.width) / 2)
          });
		  this.options.onOpenComplete.call();
          this.replaceBox();
		  
        }));
      
      } else {

        this.Box.css({
          display         : 'none',
          top             : 0
        });

        this.options.display = 0;

        $(this).delay(500, $.bind(this, this.queue));

        $(this.Content).empty();
        this.Content.removeClass();

        if(this.i==1) {
          $('#BoxOverlay').stop();
          $('#BoxOverlay').fadeOut(this.options.closeDuration, $.bind(this, function(){
            $('#BoxOverlay').hide();
           /* if (!$.support.maxHeight) { //IE6
              $('embed, object, select').css({ 'visibility' : 'visible' });
            } */

            this.togFlashObjects('visible');

            this.options.onCloseComplete.call();
          }));
        }
      }
    },

    messageBox: function(type, message, properties, input) {
        
        $(this).chain(function () {

        properties = $.extend({
          'textBoxBtnOk'        : 'OK',
          'textBoxBtnCancel'    : 'Cancelar',
          'textBoxInputPrompt'  : null,
          'password'            : false,
          'onComplete'          : function(e) {},
		  'onOpen'              : function(e) {}
        }, properties || {});

        this.options.onReturnFunction = properties.onComplete;
		this.options.onOpenFunction = properties.onOpen;

      //  this.Content.append('<div id="'+this.options.name+'-Buttons"></div>');
                      
            clase = 'Box'+type;
            
            this.Content.addClass(clase).prepend(message);
            this.display(1);	
		$("body").inputHint({
		'className': 'inputHint',
		'param': 'hint',
		'selector': 'input'
		});	 
		
		cuSel({
		changedEl: "select",
		visRows: 15,
		scrollArrows: false
		});		

      });

      this.i++;

      if(this.i==1) {
        $(this).callChain(this);
      }
    },

    queue: function() {
      this.i--;
      $(this).callChain(this);
    },

    chk: function (obj) {
      return !!(obj || obj === 0);
    },

    togFlashObjects: function(state) {
      var hideobj=new Array("embed", "iframe", "object");
      for (y = 0; y < hideobj.length; y++) {
       var objs = document.getElementsByTagName(hideobj[y]);
       for(i = 0; i < objs.length; i++) {
        objs[i].style.visibility = state;
       }
      }
    },

    preloadImages: function() {
      var img = new Array(2);
      img[0] = new Image();img[1] = new Image();img[2] = new Image();
      img[0].src = this.Box.css('background-image').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");
      img[1].src = this.InBox.css('background-image').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");
      img[2].src = this.Contenedor.css('background-image').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");
    },
    
	
    BaseWindow: function(message, properties) {
      this.messageBox('BaseWindow', message, properties);
    }

  };

})(jQuery);
