﻿/*
    Author  :   Anand Kumar Sharma
    Date    :   20-10-2009
    Purpose :   To Create modal popup window dynamically.
*/


var jqWindowsEngineZIndex = 1; 
(function($)
{ 

    /**
     * @option string windowTitle, the tile to display on the window
     * @option HTML content, the content to display on the window
     * @option string ajaxURL, URL address to load the content, this has priority over content
     * @option string iframeUrl, URL address to load the content, this has priority over content
     * @option int width, the initial width of the window
     * @option int height, the initial height of the window
     * @option int posx, the initial x position of the window
     * @option int posy, the initial y position of the window
     * @option boolean statusBar, enable or disable the window status bar
     * @option boolean minimizeButton, enable or disable the window minimize button
     * @option HTML minimizeIcon, an html text to display as the minize icon
     * @option boolean maximizeButton, enable or disable the window maximize button
     * @option HTML maximizeIcon, an html text to display as the maximize icon
     * @option boolean closeButton, enable or disable the window close button
     * @option HTML closeIcon, an html text to display as the close icon
     * @option boolean draggable, enable or disable the window dragging
     * @option boolean resizeable, enable or disable the window resize button
     * @option HTML resizeIcon, an html text to display as the resize icon
     * @option isAjax: true if need ajax to fetch the content of window, False if ajax not needed to fetch content.
     * @option sendData: Data send with ajax POST request.
     */ 
$.fn.newWindow = function(options){

    var lastMouseX = 0;
    var lastMouseY = 0;
    var wHW = GetViewPort();
    wHW[0] = wHW[0] - 20;
    wHW[1] = wHW[1] - 20;

    var defaults = 
    {
      windowTitle : "",
      domContent:"",
      content: "",
      ajaxURL: "",
      iframeURL: "",
      width : 200,
      height : 200,
      posx : 50,
      posy : 50,
      statusBar: true,
      minimizeButton: true,
      minimizeIcon: "<div class='minBrowseIcon' title='Minimize'></div>",
      maximizeButton: true,
      maximizeIcon: "<div class='maxBrowseIcon' title='Maximize'></div>",
      closeButton: true,
      closeIcon: "<div class='closeBrowseIcon' title='Close'></div>",
      draggable: true,
      resizeable: false,
      resizeIcon: "&#8756;",
      isAjax:false,
      sendData:"",
      isResizable:true,
      isElectionmall:false,
      isFull:false,
      isBrowser:false,
      isScroll:false
    };
  
    var options = $.extend(defaults, options);
    
    $windowContainer = $('<div class="window-container"><div class="window-back"></div></div>');
    $windowTitleBarOut = $('<div class="window-titleBar"></div>');
    $windowTitleBar = $('<div class="titlePadd"></div>');
	$windowTitleBarOut.append($windowTitleBar);        
    $windowMinimizeButton = $('<div class="window-minimizeButton"></div>');
    $windowMaximizeButton = $('<div class="window-maximizeButton"></div>');
    $windowCloseButton = $('<div class="window-closeButton"></div>');
    $windowContent = $('<div class="window-content"></div>');
    $windowStatusBar = $('<div class="window-statusBar"></div>');
    $windowResizeIcon = $('<div class="window-resizeIcon"></div>');
	
    var setFocus = function($obj)
    {
        $obj.css("z-index",jqWindowsEngineZIndex++);
    }
	
	var resize = function($obj, width, height)
	{
	    var nw = width;
	    var nh = height;
	    /*if(navigator.appName.search(/Internet Explorer/i) != -1)
	    {
	        nw = width + 4;
	        nh = height + 4;
	    }*/
	    $obj.attr("lastWidth",nw)
		    .attr("lastHeight",nh)
		    .css("width", nw)
	        .css("height", nh);
	        
	        if(options.isFull)
	        {
	              $obj.animate(
		          {
		            top: "25px",
			        left: "10px",
			        width: $(window).width()-20,
			        height: $(window).height()-80
		          },"slow");
		          $obj.attr("state","maximized")
	        }
	}
	
	var move = function($obj, x, y)
	{
	
	    if(x > 0 && y > 0)
        {}
        else if(x > 0 && y < 0)
        {
            y = 10;
        }
        else if(x < 0 && y > 0)
        {
            x = 5;
            
        }
        else
        {
            x = x + 5;
            y = y + 10;
        }
        
        if(x > (wHW[1]- $obj.width()) && y > (wHW[0] - ($obj.height()+20)))
        {
            x = x - 10;
            y = y - 10;
        }
        else if(x > (wHW[1]- $obj.width()) && y < (wHW[0] - ($obj.height()+20)))
        {
            x = x - 10;
        }
        else if(x < (wHW[1]- $obj.width()) && y > (wHW[0] - ($obj.height()+20)))
        {
            y = y - 10;
            
        }
        else
        {
            
        }
	    $obj.attr("lastX",x)
		    .attr("lastY",y)
		    .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;
	  
	  resize($obj, neww, newh);
	};
	
	$windowTitleBar.bind('mousedown', function(e)
	{
        $obj = $(e.target).parent().parent();
        setFocus($obj);
        if($obj.attr("state") == "normal")
        {
            e = e ? e : window.event;
	        lastMouseX = e.clientX;
	        lastMouseY = e.clientY;
		  
	           /*$(document).bind('mousemove', function(e)
	            {
		            dragging(e, $obj);
	            });
    		    
	            $(document).bind('mouseup', function(e)
	            {
		            $(document).unbind('mousemove');
	            });*/
        }
    });
	
	$windowResizeIcon.bind('mousedown', function(e)
	{
		$obj = $(e.target).parent().parent();
		setFocus($obj);
		
		if($obj.attr("state") == "normal")
		{
			e = e ? e : window.event;
			lastMouseX = e.clientX;
			lastMouseY = e.clientY;
            if(options.isResizable)
		    {
			    $(document).bind('mousemove', function(e)
			    {
				    resizing(e, $obj);
			    });

			    $(document).bind('mouseup', function(e)
			    {
				    $(document).unbind('mousemove');
			    });
			}
		}
	  
    });
	
	$windowMinimizeButton.bind('click', function(e)
	{
		$window = $(e.target).parent().parent().parent().parent();
		$toolButton = $window.data("toolButton");
		$toolButton.toggleClass("active");
		setFocus($window);
		$window.fadeToggle();
		return;
	});
	
	$windowTitleBar.bind('dblclick', function(e)
	{
	  $obj = $(e.target).parent().parent();
	  setFocus($obj);
	  if(options.isResizable)
	  {
	      if($obj.attr("state") == "normal")
	      {
		      $obj.animate(
		      {
		        top: "25px",
			    left: "10px",
			    width: $(window).width()-20,
			    height: $(window).height()-80
		      },"fast");
		      $obj.attr("state","maximized")
	      }
	      else if($obj.attr("state") == "maximized")
	      {
              $obj.animate(
              {
	            top: $obj.attr("lastY"),
		        left: $obj.attr("lastX"),
		        width: $obj.attr("lastWidth"),
		        height: $obj.attr("lastHeight")
	          },"fast");
	          $obj.attr("state","normal")
	      }
	  }
	});
	
	$windowMaximizeButton.bind('click', function(e)
	{
	  $obj = $(e.target).parent().parent().parent().parent();
	  setFocus($obj);
	  if($obj.attr("state") == "normal")
	  {
		  $obj.animate(
		  {
		    top: "25px",
			left: "10px",
			width: $(window).width()-20,
			height: $(window).height()-80
		  },"slow");
		  $obj.attr("state","maximized")
	  }
	  else if($obj.attr("state") == "maximized")
	  {
	        $obj.animate(
	        {
		        top: $obj.attr("lastY"),
			    left: $obj.attr("lastX"),
			    width: $obj.attr("lastWidth"),
			    height: $obj.attr("lastHeight")
		    },"slow");
		  $obj.attr("state","normal")
	  }
	  
    });
	
	$windowCloseButton.bind('click', function(e)
	{
        $window = $(e.target).parent().parent().parent().parent();
        if($(this).parent().text().search(/Add Applications/i) != -1 || $(this).parent().text().search(/Create Desktop Icons/i) != -1)
	    {
	        $.fn.EasyWidgets(
            {
                callbacks : 
                {
                      onChangePositions : function(str)
                      {
                            SaveWidget(str);
                      }
                }
            });
            $("ul#menubar").simplemenu();
            AddEventForMenu();
        }
        
	    $window.fadeOut(function()
	    {
            $toolButton = $window.data("toolButton");
            $toolButton.remove();
            $window.remove();
	    });
	    
	    $('.toolButton').each(function()
	    {
	        if($(this).attr('rel') == 'noview')
	        {
	            $(this).attr('rel','view').show();
	            return false;
	        }
	    });
	    var bCount = $('.toolButton').length-1;
        var iWidth = 140;
        var mWidth = 33;
        var tWidth = $('#ToolBar').innerWidth();
        if(tWidth > ((bCount * iWidth) + mWidth))
        {
            $('.taskBarPrevBtn').hide();
            $('.taskBarNextBtn').hide();
            $('.toolButton').show();
        }
	    
  });
	
	$windowContent.click(function(e)
	{
      setFocus($(e.target).parent());
    });
    
	$windowStatusBar.click(function(e)
	{
      setFocus($(e.target).parent());
    });
	
	move($windowContainer,options.posx,options.posy);
	resize($windowContainer,options.width,options.height);
	$windowContainer.attr("state","normal");
	$windowContainer.draggable({containment:'document',scroll: false}).css('position','absolute');
	$windowTitleBar.append(options.windowTitle);
	
	/*if(options.minimizeButton)
	    $windowTitleBarOut.append($windowMinimizeButton)
	if(options.maximizeButton)
	    $windowTitleBarOut.append($windowMaximizeButton)
	if(options.closeButton)  
	    $windowTitleBarOut.append($windowCloseButton);
	if(options.resizeable)
	    $windowStatusBar.append($windowResizeIcon);
	*/
	
	if(options.closeButton)    // first close
    	$windowTitleBar.append($windowCloseButton);
	
	if(options.maximizeButton)   // second maximize
		$windowTitleBar.append($windowMaximizeButton)
		
	if(options.minimizeButton)    // third minimize
		$windowTitleBar.append($windowMinimizeButton)
	
	if(options.resizeable)
		$windowStatusBar.append($windowResizeIcon);
		
	$windowContainer.append($windowTitleBarOut)
	$windowContainer.append($windowContent)
	
	if(options.statusBar)
	    $windowContainer.append($windowStatusBar);
	
	$windowContainer.hide();
	
	
	$windowContainer.bind('click', function(e)
	{
	    $obj = $(e.target).parent();
        setFocus($obj);
	});
	
	return this.each(function(index) {
		var $this = $(this);
		
		$windowMinimizeButton.html(options.minimizeIcon);
		$windowMaximizeButton.html(options.maximizeIcon);
		$windowCloseButton.html(options.closeIcon);
		$windowResizeIcon.html(options.resizeIcon);
		
		$windowContainer.data("toolButton", $this);
		$this.data("window",$windowContainer);
		$('body').append($windowContainer);
  
    $window = $this.data("window")
    if(options.ajaxURL != "")
    { 
        if(options.isAjax)
        {
            
        }
        else
        {
            $window.children(".window-content").load(options.ajaxURL);
        }
        
    }
    else if(options.iframeURL != "") 
    {
        if(options.isAjax)
        {
            $.ajax(
                        {  
                            type: "POST",
                            url: options.iframeURL,  // Send the login info to this page
                            data: { msg : options.sendData },    //equivalent to url parameter "msg=Hellow%20Nurse!"
                            async: true,    //default is asynchronous request can set to false
                            cache: false,
                            beforeSend:function()
                            {
                               $windowContainer.showoverlay({topX:0,topY:0});

                            },
                            success: function(data)
                            {  
                                $windowContainer.hideoverlay();
                                var dataFinal = data.split('~');
                                if(dataFinal.length > 1)
                                {
                                    if(dataFinal[0] == 'success')
                                    {
                                            if(options.isBrowser)
                                                $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper"><div class="dvBackPrev" ><div name=\"btnBrowser\" class="browserBack" title="Back"></div><div name=\"btnBrowser\" class="browserForward" title="Forward"></div><div name=\"btnBrowser\" class="browserRefresh" title="Refresh"></div></div><iframe src ="'+dataFinal[1]+'" class="dvIframe" frameborder="0" scrolling="auto"></iframe></div></div>');
                                            else
                                                $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper"><iframe src ="'+dataFinal[1]+'" class="dvIframe" frameborder="0" scrolling="no"></iframe></div></div>');
                                    }
                                    else
                                    {
                                        $toolButton = $window.data("toolButton");
                                        $toolButton.remove();
                                        $window.remove();
                                        window.location.assign(dataFinal[1]);
                                    }
                                }
                                
                            }
                        });  
        }
        else
        {
            if(options.isBrowser)
                 $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper"><div class="dvBackPrev"><div name=\"btnBrowser\" class="browserBack" title="Back"></div><div name=\"btnBrowser\" class="browserForward" title="Forward"></div><div name=\"btnBrowser\" class="browserRefresh" title="Refresh"></div></div><iframe src ="'+options.iframeURL+'" class="dvIframe" frameborder="0" scrolling="auto"></iframe></div></div>');
            else if(options.isScroll)
                $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper"><iframe src ="'+options.iframeURL+'" class="dvIframe" frameborder="0" style="overflow:auto; overflow-x:hidden;"></iframe></div></div>');
            else
                $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper"><iframe src ="'+options.iframeURL+'" class="dvIframe" frameborder="0" scrolling="no"></iframe></div></div>');
        }
        
        $('div[name=btnBrowser]').live("click",function()
        {
            var mainCtrl = $(this).parent().parent().find('iframe');
            if(this.className == 'browserBack')
            {
                mainCtrl.attr('src',history.go(-1));
            }
            else if(this.className == 'browserForward')
            {
                mainCtrl.attr('src',history.go(+1));
            }
            else if(this.className == 'browserRefresh')
            {
                mainCtrl.attr('src',mainCtrl.attr('src'));
            }
        });
    }
    else if (options.domContent!="") 
    {
        if(options.isAjax)
        {
            $.ajax(
                        {  
                            type: "POST",
                            url: options.domContent,  // Send the login info to this page
                            data: { msg : options.sendData },    //equivalent to url parameter "msg=Hellow%20Nurse!"
                            async: true,    //default is asynchronous request can set to false
                            cache: false,
                            beforeSend:function()
                            {
                               $windowContainer.showoverlay({topX:0,topY:0});
                            },
                            success: function(data)
                            {  
                                $windowContainer.hideoverlay();
                                var dataFinal = data.split('~');
                                if(dataFinal.length > 1)
                                {
                                    if(dataFinal[0] == 'success')
                                    {
                                        var obj = $('.window-container');
                                        var objData = $(dataFinal[1]);
		                                
                                        $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper">' + dataFinal[1] + '</div></div>');
                                    }
                                    else if(dataFinal[0] == 'redirect')
                                    {
                                        $toolButton = $window.data("toolButton");
                                        $toolButton.remove();
                                        $window.remove();
                                        window.location.assign(dataFinal[1]);
                                    }
                                    else
                                    {
                                        $toolButton = $window.data("toolButton");
                                        $toolButton.remove();
                                        $window.remove();
                                        window.location.assign(dataFinal[1]);
                                    }
                                }
                                
                                
                            }
                        });  
        }
        else
        {
		    $window.children(".window-content").append('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper">' + options.domContent.clone(true) + '</div></div>');
		}
    }
    else 
    {
        $window.children(".window-content").html('<div id="modalWindow" class="modelWindowHide"><div class="windowWrapper">' + options.content + '</div></div>');
    }
    if(!options.draggable)
        $window.children(".window-titleBar").css("cursor","default");
    setFocus($window);
		$this.addClass("active");
    $window.fadeIn();
		
		$this.click(function(event){
			event.preventDefault();   
			$window = $this.data("window");
			$this.toggleClass("active");
			setFocus($window);
			$window.fadeToggle();
		});
	});

  
}})(jQuery);


    function AddToTaskBar($obj)
	{
	    var tPrev = $('.taskBarPrevBtn');
	    var tNext = $('.taskBarNextBtn');
	    var bCount = $('.toolButton').length+1;
	    var iWidth = 140;
	    var mWidth = 66;
	    var tWidth = $('#ToolBar').innerWidth();
	    if(tWidth > ((bCount * iWidth) + mWidth))
	    {
	        $obj.attr('rel','view');
	        $('#ToolBar').append($obj);
	    }
	    else
	    {
	        $obj.attr('rel','noview');
	        $('#ToolBar').append($obj);
	        if(tPrev.is(':visible'))
	        {
	            tNext.hide();
	        }
	        else
	        {
	            tNext.show();
	        }
	        
	    }
	    if(tNext.is(':visible'))
	    {
	        $('div[rel=noview]').hide();
	    }
	    
	        
	        
	    tNext.bind('click',function()
	    {
	        $('div[rel=noview]').show();
	        $('div[rel=view]').hide();
	        tPrev.show();
	        $(this).hide();
	    });
	    tPrev.bind('click',function()
	    {
	        $('div[rel=noview]').hide();
	        $('div[rel=view]').show();
	        tNext.show();
	        $(this).hide();
	    });
	}
