$(document).ready(function(){
   //align element in the middle of the screen
   $.fn.alignCenter = function() {
      //get margin left
      var marginLeft =  - $(this).width()/2 + 'px';
      //get margin top
      var marginTop =  - $(this).height()/2 + 'px';
      //return updated element
      return $(this).css({'margin-left':marginLeft, 'margin-top':marginTop});
   };

   $.fn.togglePopup = function(opt){
     
	 var POPUP = this;
	 POPUP.option = {
		ajaxurl: '',
		width: 500,
		height: 400,
		clicktohide: 1,
		iframe: false
	 };
	 option = $.extend(POPUP.option, opt);
	 //detect whether popup is visible or not
     if($('#popup').hasClass('hidden'))
     {
       //alert(1);
	   //hidden - then display
       //when IE - fade immediately
       if($.browser.msie)
       {
         $('#opaco').height('100%').toggleClass('hidden')
                    .click(function(){$(this).togglePopup();});
       }
       else
       //in all the rest browsers - fade slowly
       {
         $('#opaco').height('100%').toggleClass('hidden')
                    .click(function(){$(this).togglePopup();});
       }

		$('#popup').prepend($(POPUP).show());
		if (POPUP.option.ajaxurl != ''){
			if (POPUP.option.iframe == true) {
				$(POPUP).css({"width": "100%", "height": "100%"});
				$('#popup').alignCenter().toggleClass('hidden');
				$('#popup').animate({
						width: POPUP.option.width,
						height: POPUP.option.height,
						marginLeft: - POPUP.option.width/2 + 'px',
						marginTop: - POPUP.option.height/2 + 'px'
					}, 400, function(){
						$('#popup').css({display: ""});
						$(POPUP).html('<iframe border="0" style="border: none" src="'+ POPUP.option.ajaxurl +'" width="100%" height="100%"></iframe>');
					});
			} else {
				$(POPUP).html('<div align="center"><img src="/img/admin/loading.gif"></div>');
				$('#popup').alignCenter().toggleClass('hidden');
				$.ajax({
				  url: POPUP.option.ajaxurl,
				  success: function(data) {
					$(POPUP).html('').css({height: 24});
					$('#popup').animate({
						width: POPUP.option.width,
						height: POPUP.option.height,
						marginLeft: - POPUP.option.width/2 + 'px',
						marginTop: - POPUP.option.height/2 + 'px'
					}, 400, function(){
						$('#popup').css({display: ""});
						$(POPUP).html(data);
					});
					
				  }
				});
			}
		} else
		   $('#popup').width(POPUP.option.width).height(POPUP.option.height)
			 .alignCenter()
			 .toggleClass('hidden');
     }
     else
     {
       //visible - then hide
       $('#opaco').toggleClass('hidden').removeAttr('style').unbind('click');
       $('#popup').toggleClass('hidden').css({width: "", height: ""});
     }
   };
});
