(function($) {
  $.fn.overlay = function(){
    return this.bind('click', function(){
      $$ = $(this);
      var url;

      getUrl();

      function destroy(){
        overlay.left = $('div.overlay').offset().left;
        overlay.top = $('div.overlay').offset().top;

        $('div.overlay').animate({opacity: 0}, 500, function(){
          $(this).remove();
        });
        overlay.visible = false;
        $('div#window').animate({opacity: 0}, 500, function(){
          $(this).remove();
        });
        showSelects();
        
        if ($('div#center object').length) {
          $('div#center object').fadeIn(500);
        };
        
        return false;
      };

      function bindings(){
        if ($('div.overlay .overlay').length > 0){
          $('div.overlay .overlay').overlay();
        };

        if ($('div.overlay form').length > 0) {
          $('div.overlay :input:first').focus();

          if ($('div.overlay form input:file').length > 0){
            url = $(this).attr('action');

            var options = {
              contentType: 'application/x-javascript-form-urlencoded',
              type: 'POST',
              dataType: 'html',
              url: url,
              timeout: 3000,
              success: function(data) { 
                if (data === 'x'){
                  $('a.addressbook').click();
                }else{
                  resize(data);
                };
              }
            };

            $('div.overlay form').ajaxForm(options);
          } else{
            
            $('div.overlay form').submit(function(){
              url = $(this).attr('action');
              function formToArray(){
                var a = [];

                els = $('div.overlay_content input:not(.formsubmit), div.overlay_content select, div.overlay_content textarea');

                for (var i=0; i < els.length; i++) {
                  var el = els[i];

                  if ($(el).filter(':checkbox').length > 0){
                    if ($(el).filter(':checkbox:checked').length > 0){
                      a.push({name: el.name, value: el.value});
                    } else{

                    };
                  } else{
                    a.push({name: el.name, value: el.value});
                  };
                };

                return a;
              };

              formArray = formToArray();

              $.ajax({
                contentType: 'application/x-javascript-form-urlencoded',
                dataType: 'html',
                timeout: 3000,
                type: 'POST',
                data: formArray,
                url: url,
                error: function(){
                },
                success: function(data){
                  if (data === 'x'){
                    window.location = window.document.location.href;
                  }else{
                    resize(data);
                  };
                },
                complete: function(data){
                }
              });

              return false;
            });
          };
          
          if ($('div.overlay a.address_detail').length > 0){
						$('a.choose_all').toggle(function() {
							var arr = $('div.address_list input:not(:checked)');
							
							for (var i=0; i < arr.length; i++) {
								$(arr[i]).select();
							};
							
							$(this).text('Auswahl aufheben').attr({title: 'Auswahl aufheben'});
						}, function() {
							var arr = $('div.address_list input:checked');
							
							for (var i=0; i < arr.length; i++) {
								$(arr[i]).click();
							};
							
							$(this).text('Alle auswählen').attr({title: 'Alle auswählen'});
						});
						
            $('div.overlay a.address_detail').bind('click', function(){
							url = $(this).attr('href');
              
              $.ajax({
                contentType: 'application/x-javascript-form-urlencoded',
                dataType: 'json',
                timeout: 3000,
                type: 'GET',
                url: url,
                error: function(){
                  
                },
                success: function(data){
                  var address = data;
                  
                  if (address.title === null | address.title === ''){
                    address.title = '&nbsp;';
                  };
                  if (address.firstname === null | address.firstname === ''){
                    address.firstname = '&nbsp;';
                  };
                  if (address.lastname === null | address.lastname === ''){
                    address.lastname = '&nbsp;';
                  };
                  if (address.company === null | address.company === ''){
                    address.company = '&nbsp;';
                  };
                  if (address.add_on === null | address.add_on === ''){
                    address.add_on = '&nbsp;';
                  };
                  if (address.street === null | address.street === ''){
                    address.street = '&nbsp;';
                  };
                  if (address.zip === null | address.zip === ''){
                    address.zip = '&nbsp;';
                  };
                  if (address.city === null | address.city === ''){
                    address.city = '&nbsp;';
                  };
                  if (address.country === null | address.country === ''){
                    address.country = '&nbsp;';
                  };
                  if (address.eamil === null | address.email === ''){
                    address.email = '&nbsp;';
                  };
                  if (address.phone === null | address.phone === ''){
                    address.phone = '&nbsp;';
                  };
                  if (address.birthday === null | address.birthday === ''){
                    address.birthday = '&nbsp;';
                  };
                  if (address.anniversary === null | address.anniversary === ''){
                    address.anniversary = '&nbsp;';
                  };
                  
                  var name = address.firstname + ' ' + address.lastname;
                  var post = address.zip + ' ' + address.city;
                  
                  $('div.overlay p.title').empty().prepend(address.title);
                  $('div.overlay p.name').empty().prepend(name);
                  $('div.overlay p.company').empty().prepend(address.company);
                  $('div.overlay p.add_on').empty().prepend(address.add_on);
                  $('div.overlay p.street').empty().prepend(address.street);
                  $('div.overlay p.post').empty().prepend(post);
                  $('div.overlay p.country').empty().prepend(address.country);
                  $('div.overlay p.email').empty().prepend(address.email);
                  $('div.overlay p.phone').empty().prepend(address.phone);
                  $('div.overlay p.birthday').empty().prepend(address.birthday);
                  $('div.overlay p.anniversary').empty().prepend(address.anniversary);
                },
                complete: function(){
                  
                }
              });
              
              overlay.addclick = overlay.addclick +1;
              return false;
            });
          };
        };

        /*document.onkeyup = function(e){
        	if (e == null) { // ie
        		keycode = destroy();
        	} else { // mozilla
        		keycode = e.which;
        	}
        	if(keycode == 27){ // close
            destroy();
        	}	
        };*/
        
        $(':input').focus(function(){
          $(this).css({border: '1px solid #cc66cc'});
        });
        $(':input').blur(function(){
          $(this).css({border: '1px solid #ccc'});
        });
        
        $('a.close').bind('click', destroy);
      };

      function pageSize(){
        var d = document.documentElement;
    		var w = window.innerWidth	  || self.innerWidth	|| (d && d.clientWidth)		|| document.body.clientWidth;
    		var h = window.innerHeight	|| self.innerHeight	|| (d && d.clientHeight)	|| document.body.clientHeight;

    		var t = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;

    		return[w,h,t];
      };

      function oTop(){
        p = pageSize();
        t = p[2];
        h = p[1];
        o = $('div.overlay').offset().top;
        r = t-o;

        if (r > 10){
          overlay.top = (t + (h/8));
        };
        if (r < 0){
          overlay.top = (t + (h/4));
        };
      };

      function show(){
        bindings();
        
        /*if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
    			$("body","html").css({height: "100%", width: "100%"});
    			$("html").css("overflow","hidden");
    			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
    				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
    				$("#TB_overlay").click(destroy);
    			}
    		}else{
    			if(document.getElementById('window') === null){
    				$("body").append('<div id="window"></div>');
    				$('#window').click(destroy);
    			}
    		};*/
        if ($('div#center object').length) {
          $('div#center object').fadeOut(500);
        };
        
        $('div.overlay').css({opacity: 0, display: 'block', top: overlay.top + 'px', left: overlay.left + 'px', width: overlay.width, height: overlay.height}).animate({opacity: 1}, 500, function(){
					if ($('div#stageapp').length) {
					
					} else {
						$(this).draggable({delay: 10, zIndex: 10005, containment: 'body'});
					};
        });
        
        
        overlay.visible = true;

        hideSelects();
      };

      function hideSelects(){
        if($.browser.msie && $.browser.version == '6.0')
        {
          $('#page select').hide();
        }
      }

      function showSelects(){
        if($.browser.msie && $.browser.version == '6.0')
        {
          $('#page select').show();
        }
      }

      function resize(data){
        nd = $(data);
        if ($.browser.msie) {
          var a_close = $('div.overlay a.close');
          $('div.overlay a.close').animate({opacity: 0}, 500, function(){
            $(this).remove();
          });
        }
        $('div.overlay_content').animate({opacity: 0}, 500, function(){
          $(this).remove();
          bindings();
        });
        nd.filter('.overlay_content').css({opacity: 0}).prependTo('div.overlay').end();
        // FIXME: width and height are not from the propper element here
        w = $('*', nd).width();
        h = $('*', nd).height();
        
        overlay.width = w+30;
        overlay.height = h+70;
        if ($.browser.msie){
          $('div.overlay').animate({width: overlay.width + 'px', height: overlay.height + 'px', top: overlay.top + 'px'}, 500, function(){
            a_close.prependTo('div.overlay_content');
            $('a.close').bind('click', destroy);
            $('div.overlay a.close').animate({opacity: 1}, 300);
            $('div.overlay_content').animate({opacity: 1}, 100);
          });
        }else{
          $('div.overlay a.close').animate({opacity: 0}, 1);
          $('div.overlay').animate({width: overlay.width + 'px', height: overlay.height + 'px', top: overlay.top + 'px'}, 500, function(){
            $('div.overlay_content').animate({opacity: 1}, 100);
            $('div.overlay a.close').animate({opacity: 1});
          });
        };
      };

      function position(){
        pageSize = pageSize();

        overlay.left = (pageSize[0] - overlay.width) / 2;
        overlay.top = (pageSize[1] - overlay.height) / 2;

        if (overlay.top < 10) {
        	overlay.top = 10;
        }
        
        if (overlay.left < 10) {
        	overlay.left = 10;
        }

        overlay.top += typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;

        overlay.created = true;
        show();
      };

      function dimensions(){
        setTimeout(function(){
          if($.browser.msie && $.browser.version == "6.0") {
            var slc = 'div.overlay_content:first';
          } else 
            var slc = 'div.overlay';
          overlay.width = $(slc).width();
          overlay.height = $(slc).height();
          
          if (overlay.created == false || $('div#stageapp').length > 0){
            position();
          }else{
            show();
          };
        }, 1);
      };

      function getContent(){  
        if($('div.overlay').length == 0)
          $('<div class="overlay" />').prependTo('body');
        $.ajax({
          contentType: 'application/x-javascript-form-urlencoded',
          dataType: 'html',
          timeout: 3000,
          type: 'GET',
          url: url,
          error: function(){

          },
          success: function(data){
            overlay.url = url;
            overlay.data = data;
            if(overlay.visible === true){
              resize(data);
            }else{
              nd = $(data);
              //nd.prependTo('div.overlay');
              $('div.overlay').filter('.overlay_content').remove();
              nd.prependTo('div.overlay');
							$('div.overlay div#stageapp').html(overlay.stage);
              // if the html snippet contains images, we run dimension after fully loaded
              if($('img', nd).length) {
                if($.browser.msie)
                  dimensions();
                else
                  $('img', nd).load(function() {dimensions()});
              } else {
                dimensions();
              }
            };
          },
          complete: function(data){
          }
        });
      };

      function check(){
        if (url === undefined){

        }else{
          if (overlay.url === url){
            if (overlay.visible) {
            } else{
              getContent(); 
            };
          } else{
            getContent();
          };
        };
      };

      function getUrl(){
        if ($$.attr('longdesc')) {
          url = $$.attr('longdesc');
          check();
        }else{
          url = $$.attr('href');

          check();
        };
      };

      return false;
    });
  };
})(jQuery);

var overlay = Object({
  width: 0,
  height: 0,
  left: 0,
  top: 0,

  url: undefined,
  data: undefined,
  created: false,
  visible: false
});