/*

	jQuery window plugin
	Copyright (c) 2010 Gael Jaunin

	For support and tutorials visit
	http://www.xuserver.net/

	License: GNU Lesser General Public License (LGPL) 
	at http://opensource.org/licenses/lgpl-2.1.php

	This plugin is free software;  you can redistribute it  and/or  modify  it 
	under the terms of the GNU Lesser General Public License as  published  by 
	the Free Software Foundation;  either version 2.1 of the License,  or  (at 
	your option) any later version.
	This software is distributed in the hope  that  it  will  be  useful,  but 
	WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
	or FITNESS FOR A PARTICULAR PURPOSE.  See the  GNU Lesser  General  Public 
	License for more details.
	You should have received a copy of  the  GNU Lesser General Public License 
	along with this library;  if not,  write to the  Free Software Foundation, 
	Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

	THIS COMMENT AND COPYRIGHT NOTICE MUST BE RETAINED IN THE CODE AS IS FOR LEGAL USE

*/


(function($){
  $.fn.extend({
	windowBlink: function(options){
      var defaults = {
        times:2,
        speed:100,
        onBlink:null,
        onStart:null,
        onComplete:null
			};
			
			var options =  $.extend(defaults, options);
      blinkCount = options.times*2;
      if(options.onStart != null){ options.onStart(); };
      do {
        if($(this).attr('stopBlink')){break;};
        $(this)['fade'+(blinkCount%2==0?'Out':'In')](options.speed);
        if(blinkCount%2==0 && options.onBlink != null){ options.onBlink(); };
        if(blinkCount ==1 && options.onComplete != null){ 
          setTimeout(function(){options.onComplete()}, options.times * options.speed *2 );
        };          
      }while (--blinkCount);
      $(this).attr('stopBlink','');    
      return this;
    },
    
    jxWindow: function(opt) {
			var defaults = {
				title: $(this).attr('title'),
        event:'click',
        isModal: false,
				isUnique : true,
				isDock : false,
				width:300,
				height:200,
				posx:'undefined',
				posy:'undefined',
				maximized:false,
				minimizeButton: true,
        maximizeButton: true,
        closeButton: true,
        draggable: true,
        resizeable: true,
        urlType:false
			};				
			var opt =  $.extend(defaults, opt);
			
			return this.each(function() {
        var jxId =Math.ceil(100000000*Math.random());
        var options = opt;
		    var $obj = $(this);
				
				if($obj.attr('id') =="")$obj.attr('id' ,jxId );
        $obj.attr('jxId',$obj.attr('id'));
        $obj.attr('id','a-'+$obj.attr('id'));
				$obj.attr('jxHref', $obj.attr('href'));
        $obj.attr('jxContent','');
        $obj.attr('href','javascript:void(0);');
        if(options.title==""){options.title="window";}else{options.title = $obj.attr('title');};
        
        if(isImage($obj.attr('jxHref'))){                   
          var image = new Image();
          image.src = $obj.attr('jxHref');
          options.urlType = 'urlAnImage'; 
          $obj.attr('urlType', 'urlAnImage');
        }else if(  $('#'+$obj.attr('jxHref')).width() != null  ){                   
          $('#'+$obj.attr('jxHref')).hide();
          $obj.attr('jxContent', $obj.attr('jxHref')) ;
          $obj.attr('jxHref' , '');
          
          $obj.attr('urlType', 'hiddenDiv');
        }else if(isExternalLink($obj.attr('jxHref'))){
          options.title = $obj.attr('jxHref');
          options.urlType = 'externalUrl';
          $obj.attr('urlType', 'externalUrl'); 
        };
        $obj.attr('title', options.title);        
        $obj.bind(options.event,function (e){
          if(options.posx == 'undefined' || options.posx == 'mouse' ){options.posx = e.pageX+10}
          if(options.posy == 'undefined' || options.posy == 'mouse' ){options.posy = e.pageY+10}
          if(options.posx == 'center'){options.posx = ($(window).width()-options.width)/2; }
          if(options.posy == 'center'){options.posy = ($(window).height()-options.height)/2; }
                    
          if($obj.attr('panel')==null || $obj.attr('panel')==""){ 
            jQuery.jxwindow({
              id:$(this).attr('jxId'),
              title:$obj.attr('title'),
              content : $obj.attr('jxContent'),
              url:$obj.attr('jxHref'),
              isUnique:true,
              isModal:options.isModal,
              isDock:options.isDock,
              posx: options.posx,
              posy: options.posy,
              maximized:options.maximized,
              width:options.width,
				      height:options.height,
				      statusBar: true,
              minimizeButton: options.minimizeButton,
              maximizeButton: options.maximizeButton,
              closeButton: options.closeButton,
              draggable: options.draggable,
              resizeable: options.resizeable,
              urlType : $obj.attr('urlType')
            });
            
          }else{     
            options.isDock.tabs('select', '#' + $(this).attr('panel'));            
          };
        });
      });
    }
    
	}); 
})(jQuery);



jQuery.extend({
  jxwindow: function(options){  
    var lastMouseX = 0;
    var lastMouseY = 0;
    var tempsId = 'jxw_'+Math.ceil(100000000*Math.random());
    var defaults = {
      id: tempsId,
      title: "window",
      width: 300,
      height: 200,
      posx: 50,
      posy: 50,
      maximized:false,
      content: "",
      url : "",
      isUnique:false,
      isModal:false,
      isDialog:false,
      isDock:false,
      onDragBegin: null,
      onDragEnd: null,
      onResizeBegin: null,
      onResizeEnd: null,
      onWindowClose: null,
      onAjaxContentLoaded: null,
      statusBar: true,
      minimizeButton: true,
      maximizeButton: true,
      closeButton: true,
      draggable: true,
      resizeable: true,
      urlType : false,
      hiddenDivParent:$('body')
    };
  
    var options = $.extend(defaults, options);
    if(options.posx == 'center'){options.posx = ($(window).width()-options.width)/2; }
    if(options.posy == 'center'){options.posy = ($(window).height()-options.height)/2; }
    
    var idAttr = "";
    var ajaxloader = "";
    if(options.urlType=='urlAnImage'){
      var image = new Image();image.src = options.url;
      if(image.width > image.height){
        do{image.height=image.height*0.8;image.width=image.width*0.8;}while(image.width > 450); 
      };
      if(image.height > image.width){
        do{image.height=image.height*0.8;image.width=image.width*0.8;}while(image.height > 400);
      };
      options.content = $('<img src="'+options.url+'" height="'+image.height+'" width="'+image.width+'" />');
      options.width = image.width+2;options.height= image.height+2;
      options.title = '<span class="ui-icon ui-icon-image" style="float:left;margin:5px 1px 0px 3px"></span> '+options.title;
      options.url = '';      
    }else if(options.urlType=='externalUrl'){
      options.title = '<span title="external url" class="ui-icon ui-icon-extlink" style="float:left;margin:5px 1px 0px 3px"></span> '+options.title;
      options.content = $('<iframe frameborder="0" scrolling="auto" src="'+options.url+'" width="'+options.width+'" height="'+options.height+'"/>');
      options.url = '';
    }else if(options.urlType=='hiddenDiv'){
      options.title = '<span title="hidden div" class="ui-icon ui-icon-document" style="float:left;margin:2px 0px 0px 2px"></span> '+options.title;
      options.hiddenDivParent = $('#'+options.content).parent();
      options.content = $('#'+options.content);
      options.content.show();
      options.url = '';
    };
    
    if(options.url != ""){
      ajaxloader = '<div style="height:50px;width:20px;float:left;" class="ui-autocomplete-loading"></div>';		
    };    
    if(options.isModal){
      $.buildOverlay({id:options.id, isDialog:options.isDialog});
    };
        
    
    if( $('#'+options.id+'-window-content').attr('class') == null ){  
    }else{
      if(options.isUnique){
        $('#'+options.id).windowBlink().css("z-index",jxwZindex++);
        if(options.url !=""){ 
          $('#'+options.id+'-window-content').html(ajaxloader);
          $.updateWindowContentWithAjax(options.id, options.url , false);
          return false;
        }else{
          return false;
        };
        setFocus($('#'+options.id));
      }else{ 
        if(options.url !=""){ 
          options.id = options.id+Math.ceil(100000000*Math.random());
        }else{ 
          options.id = options.id+Math.ceil(100000000*Math.random());
        };
      };       
    };
    
    if(options.id != ""){idAttr = 'id="'+options.id+'"';};    
    $windowContainer = $('<div '+idAttr+' style="position:absolute;" class="ui-widget window-container"></div>');
    $titleBar = $('<div style="overflow:hidden;white-space:nowrap;" class="jxwindow-titlebar ui-widget ui-widget-header ui-corner-top ui-helper-clearfix"></div>');
    $windowCloseButton = $('<div id="'+options.id+'-close-button" style="cursor:pointer" class="jxwindow-button jx-inline ui-state-default ui-corner-all window-closeButton" ><span class="ui-icon ui-icon-close"></span></div>');
    if(options.isDock){
      $windowMinimizeButton = $('<div id="'+options.id+'-min-button" style="cursor:pointer" class="jxwindow-button jx-inline ui-state-default ui-corner-all window-minimizeButton" ><span class="ui-icon ui-icon-pin-s"></span></div>');    
    }else{
      $windowMinimizeButton = $('<div id="'+options.id+'-min-button" style="cursor:pointer" class="jxwindow-button jx-inline ui-state-default ui-corner-all window-minimizeButton" ><span class="ui-icon ui-icon-minus"></span></div>');
    };
    $windowMaximizeButton = $('<div id="'+options.id+'-max-button" style="cursor:pointer" class="jxwindow-button jx-inline ui-state-default ui-corner-all window-maximizeButton" ><span class="ui-icon ui-icon-plus"></span></div>');
    $titleBarContent = $('<div style="cursor:move;padding-left:10px;width:80%;height:20px;font-weight: normal;" class="jx-inline ui-widget">'+options.title+'</div>');    
    $windowStatusBar = $('<div id="" style="border-top:0px" class="ui-widget-header ui-corner-bottom ui-helper-clearfix"></div>');
    $windowResizeIcon = $('<div class="" ><span style="cursor: se-resize;float:right" class="ui-icon ui-icon-grip-diagonal-se"></span></div>');
    
    $windowContent = $('<div id="'+options.id+'-window-content" style="height:100%;overflow:auto;" class="window-content ui-widget-content">'+ajaxloader+'</div>');
    
    $titleBar.append($windowCloseButton);
    $titleBar.append($windowMinimizeButton);
    $titleBar.append($windowMaximizeButton);
    $titleBar.append($titleBarContent);
    if(options.resizeable){$windowStatusBar.append($windowResizeIcon);};  
    
    $windowContent.append(options.content);    
    
    $windowContainer.append($titleBar);
    
    $windowContainer.append($windowContent);
    
    if(options.statusBar){$windowContainer.append($windowStatusBar);};
  
	var setFocus = function($obj){
    $('.jxwindow-titlebar').removeClass('ui-state-hover');
    $obj.children('.jxwindow-titlebar').addClass('ui-state-hover');
    $obj.css("z-index",jxwZindex++);
	};
	
	var resizeMe = function($obj, width, height){
		width = parseInt(width);
		height = parseInt(height);
		$obj.data("lastWidth",width).data("lastHeight",height);
		width = width+"px";
		height = height+"px";
		$obj.css("width", width).css("height", height);	   
	};
	
	var move = function($obj, x, y){
		x = parseInt(x);
		y = parseInt(y);
		$obj.data("lastX",x).data("lastY",y);
    x = x+"px";
		y = y+"px";		
		$obj.css("left", x).css("top", y);
	};

	var dragging = function(e, $obj){
	  if(options.draggable){
      e = e ? e : window.event;
      var newx = parseInt($obj.css("left")) + (e.clientX - lastMouseX);
      var newy = parseInt($obj.css("top")) + (e.clientY - lastMouseY);
      lastMouseX = e.clientX;
      lastMouseY = e.clientY;          
      move($obj,newx,newy);
		};
	};
	
	var resizing = function(e, $obj){
    e = e ? e : window.event;
    var w = parseInt($obj.css("width"));
    var h = parseInt($obj.css("height"));
    w = w<100 ? 100 : w;
    h = h<50 ? 50 : h;
    var neww = w + (e.clientX - lastMouseX);
    var newh = h + (e.clientY - lastMouseY);
    lastMouseX = e.clientX;
    lastMouseY = e.clientY;
    resizeMe($obj, neww, newh);
	};
	
  var resizeIframe = function($obj){
    if(options.urlType=='urlAnImage'){
      options.content.width(($obj.height()*options.width/options.height) - 3);
      options.content.height($obj.height() -3);
    }else if(options.urlType=='externalUrl'){
      options.content.width($obj.width() - 3);
      options.content.height($obj.height() -3);
    };
  };
    
	$titleBarContent.bind('mousedown', function(e){
    var $obj = $("#"+options.id);
    setFocus($obj);
    if($obj.data("state") != "maximized"){
      e = e ? e : window.event;
      lastMouseX = e.clientX;
      lastMouseY = e.clientY;
      $(document).bind('mousemove', function(e){
        dragging(e, $obj);
      });
      $(document).bind('mouseup', function(e){
        if(options.onDragEnd != null){options.onDragEnd();};
        $(document).unbind('mousemove');
        $(document).unbind('mouseup');
      });
      if(options.onDragBegin != null){options.onDragBegin();};
    };
  });
	
	$windowResizeIcon.bind('mousedown', function(e){
		var $obj = $("#"+options.id);
    setFocus($obj);	
    if($obj.data("state") === "normal"){
    	e = e ? e : window.event;
    	lastMouseX = e.clientX;
    	lastMouseY = e.clientY;    
    	$(document).bind('mousemove', function(e){
    		resizing(e, $obj);
    		resizeIframe($obj);
    	});    
    	$(document).bind('mouseup', function(e){
    		if(options.onResizeEnd != null){options.onResizeEnd();};
    		$(document).unbind('mousemove');
    		$(document).unbind('mouseup');
    	});    	
    	if(options.onResizeBegin != null){options.onResizeBegin();};
    }
  });
	
	$windowMinimizeButton.bind('click', function(e){	  
    var $obj = $("#"+options.id);
    if(options.isDock){
      options.isDock.bind( "tabsadd", function(event, ui) {
        options.isDock.tabs('select', '#' + ui.panel.id);
        if($('#a-'+options.id).attr('panel')==null || $('#a-'+options.id).attr('panel')==""){
          $('#a-'+options.id).attr('panel',ui.panel.id);
        };               
      });
      options.isDock.bind( "tabsremove", function(event, ui) {
        if($('#a-'+options.id).attr('panel')==ui.panel.id){
          $('#a-'+options.id).attr('panel','');
        };                
      });
      options.isDock.tabs({ cache: true });
      options.isDock.tabs('option', 'closable', true);
      options.isDock.tabs('add', options.url, options.title);
      $.closeWindow(options.id);
      return true;
    };
    
    setFocus($obj);
    if($obj.data("state") === "minimized"){
      $obj.data("state", "normal");
      $obj.css("height", $obj.data("lastHeight"));
      $obj.find(".window-content").slideToggle("slow");
    }else if($obj.data("state") === "normal"){
      $obj.data("state", "minimized");
      $obj.find(".window-content").slideToggle("slow", function(){$obj.css("height", 0);});
    }else{
      $obj.find(".window-maximizeButton").click();
    };
  });
	
	$windowMaximizeButton.bind('click', function(e){
    var $obj = $("#"+options.id);
    setFocus($obj);
    if($obj.data("state") === "minimized"){
        $obj.find(".window-minimizeButton").click();
    }else if($obj.data("state") === "normal"){
      $obj.animate({
          top: "30px",
          left: "20px",
          width: $(window).width()-52,
          height: $(window).height()-$windowStatusBar.height()-80
      },"slow",function(){
        resizeIframe($obj);
        $(window).scrollTop(0);
      });
      $obj.data("state","maximized");
    }else if($obj.data("state") === "maximized"){
      $obj.animate({
          top: $obj.data("lastY"),
          left: $obj.data("lastX"),
          width: $obj.data("lastWidth"),
          height: $obj.data("lastHeight")
      },"slow",function(){
        resizeIframe($obj);
      });
      $obj.data("state","normal");
    };
	});
	$titleBar.bind('dblclick', function(e){
    $windowMaximizeButton.click();
  });
	
	
	$windowCloseButton.bind('click', function(e){
    var $window = $("#"+options.id);
    $window.fadeOut(function(){ 
      if(options.urlType=='hiddenDiv'){
        options.content.hide();
        options.hiddenDivParent.prepend(options.content);      
      };
      $window.remove(); 
    });
    $.removeOverlay();
	  if(options.onWindowClose != null){options.onWindowClose();};
  });
	
	$windowContent.click(function(e){
      setFocus($("#"+options.id));
  });
  
	$windowStatusBar.click(function(e){
      setFocus($("#"+options.id));
  });
	
	move($windowContainer,options.posx,options.posy);
	resizeMe($windowContainer,options.width,options.height);
	$windowContainer.data("state","normal");
	$windowContainer.css("display","none");
  $('body').append($windowContainer);
  
  if(!options.closeButton) $windowCloseButton.css('display','none');
  if(!options.minimizeButton) $windowMinimizeButton.css('display','none');
  if(!options.maximizeButton) $windowMaximizeButton.css('display','none');
  
  $window = $windowContainer;
  if(!options.draggable){$window.children(".window-titleBar").css("cursor","default");};
  setFocus($window);
  if(options.maximized){
   $windowContainer.find(".window-maximizeButton").click();
  }
  $window.fadeIn();
  if(options.url !=""){$.updateWindowContentWithAjax(options.id,options.url);}
  $('.jxwindow-button').hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); });
  
    
},

// v1.2 : fork by GJ


closeModal: function(id){
	  $.removeOverlay();
	  $.closeWindow(id);  
	},

// v1.1 : original by HA
updateWindowContent: function(id, newContent){
  $("#" + id + " .window-content").html(newContent);
},

updateWindowContentWithAjax: function(id, url, cache){
  cache = cache===undefined ? true : false;
  $.ajax({
    url: url,
    cache: cache,
    dataType: "html",
    success: function(data) {
      $("#" + id + " .window-content").html(data);
    },
    error:function (xhr, ajaxOptions, thrownError){
      $("#" + id + " .window-content").html("<h1>ERROR "+xhr.status+"</h1><pre>cannot load page "+url+"</pre>");
    }
  });
},

moveWindow: function(id, x, y){
  $obj = $("#" + id);
  x = parseInt(x);
  y = parseInt(y);
  $obj.data("lastX",x).data("lastY",y);
  x = x+"px";
  y = y+"px";		
  $obj.css("left", x).css("top", y);
},

resizeWindow: function(id, width, height){
  $obj = $("#" + id);
  width = parseInt(width);
  height = parseInt(height);
  $obj.data("lastWidth",width).data("lastHeight",height);
  width = width+"px";
  height = height+"px";
  $obj.css("width", width).css("height", height);	
},

minimizeWindow: function(id){
  $("#" + id + " .window-minimizeButton").click();
},

maximizeWindow: function(id){
  $("#" + id + " .window-maximizeButton").click();
},

showWindow: function(id){
  $("#" + id + "").fadeIn();
},

hideWindow: function(id){
  $("#" + id + "").fadeOut();
},

closeWindow: function(id){
  $("#" + id + "-close-button").click();
},

closeAllWindows: function(){
  $(".window-container .window-closeButton").click();
}

});
