﻿/*
    Author  :   Anand Kumar Sharma
    Date    :   20-10-2009
    Purpose :   To Create modal popup window dynamically.
	uses example 
	<a href=\"zoneclock.aspx?zclk=1\" title=\"Zone Clock\" rel=\"domcontent|780x400|ajax\" class=\"paddLeftSubMenu\" id=\"A1\">
	<a href=\"zoneclock.aspx?zclk=1\" title=\"Zone Clock\" rel=\"iframe|780x400|ajax\" class=\"paddLeftSubMenu\" id=\"A1\">
	<a href=\"zoneclock.aspx?zclk=1\" title=\"Zone Clock\" rel=\"iframe|780x400\" class=\"paddLeftSubMenu\" id=\"A1\">
	<a href=\"zoneclock.aspx?zclk=1\" title=\"Zone Clock\" rel=\"domcontent|780x400\" class=\"paddLeftSubMenu\" id=\"A1\">
									$toolButton = $('<div class="toolButton">' + title + '</div>');
		                            
		                            $toolButton.newWindow(
		                            {
			                            windowTitle: title,
			                            iframeURL: href,
			                            width: parseInt(width),
			                            height: parseInt(height),
			                            isAjax:true
		                            });
									
									$toolButton.newWindow(
		                            {
			                            windowTitle: title,
			                            iframeURL: href,
			                            width: parseInt(width),
			                            height: parseInt(height),
			                            isAjax:false
		                            });
									
									$toolButton.newWindow(
		                            {
			                            windowTitle: title,
			                            domContent: href,
			                            width: parseInt(width),
			                            height: parseInt(height),
			                            isAjax:true
		                            });
									$toolButton.newWindow(
		                            {
			                            windowTitle: title,
			                            domContent: href,
			                            width: parseInt(width),
			                            height: parseInt(height),
			                            isAjax:false
		                            });
*/



var jqWindowsEngineZIndex = 100; 
(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 defaults = 
    {
      windowTitle : "",
      domContent:"",
      content: "",
      ajaxURL: "",
      iframeURL: "",
      width : 200,
      height : 200,
      posx : 450,
      posy : 200,
      statusBar: true,
      //minimizeButton: false,
      //minimizeIcon: "<img src='grfx/btnMinBrowser.png' class='changePng' title='Minimize' />",
      //maximizeButton: true,
      //maximizeIcon: "<img src='grfx/btnMaxBrowser.png' class='changePng' title='Maximize' />",
      closeButton: true,
      closeIcon: "<img src='grfx/btnCloseBrowser.png' class='changePng' title='Close' />",
      draggable: true,
      resizeable: false,
      resizeIcon: "&#8756;",
      isAjax:false,
      sendData:"",
      isResizable:true,
      isElectionmall:false
    };
  
    var options = $.extend(defaults, options);
    
    $windowContainer = $('<div class="window-container"><div class="window-back"></div></div>');
    $windowTitleBar = $('<div class="window-titleBar"></div>');        
    //$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)
	{
	    $obj.attr("lastWidth",width)
		    .attr("lastHeight",height)
		    .css("width", width)
	        .css("height", height);
	}
	
	var move = function($obj, x, y)
	{
	    $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();
        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();
//		$toolButton = $window.data("toolButton");
//		$toolButton.toggleClass("active");
//		setFocus($window);
//		$window.fadeToggle();
//		return;
//	});
	
	//$windowTitleBar.bind('dblclick', function(e)
//	{
//	  $obj = $(e.target).parent();
//	  setFocus($obj);
//	  if(options.isResizable)
//	  {
//	      if($obj.attr("state") == "normal")
//	      {
//		      $obj.animate(
//		      {
//		        top: "20px",
//			    left: "10px",
//			    width: $(window).width()-65,
//			    height: $(window).height()-75
//		      },"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();
//	  setFocus($obj);
//	  if($obj.attr("state") == "normal")
//	  {
//		  $obj.animate(
//		  {
//		    top: "50px",
//			left: "10px",
//			width: $(window).width()-65,
//			height: $(window).height()-75
//		  },"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();
        if($(this).parent().text().search(/Link Accounts/i) != -1)
	    {
	        $.fn.EasyWidgets(
            {
                callbacks : 
                {
                      onChangePositions : function(str)
                      {
                            SaveWidget(str);
                      }
                }
            });
            $("ul#menubar").simplemenu();
        }
        
	    $window.fadeOut(function()
	    {
            $toolButton = $window.data("toolButton");
            $toolButton.remove();
            $window.remove();
	    });
	    
  });
	
	$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");
	$windowTitleBar.append(options.windowTitle);
	
//	if(options.minimizeButton)
//	    $windowTitleBar.append($windowMinimizeButton)
//	if(options.maximizeButton)
//	    $windowTitleBar.append($windowMaximizeButton)
	if(options.closeButton)  
	    $windowTitleBar.append($windowCloseButton);
	
	if(options.resizeable)
	    $windowStatusBar.append($windowResizeIcon);
	
	$windowContainer.append($windowTitleBar)
	$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,
                            success: function(data)
                            {  
                                $windowContainer.hideoverlay();
                                var dataFinal = data.split('~');
                                if(dataFinal.length > 1)
                                {
                                    if(dataFinal[0] == 'success')
                                    {
                                            $window.children(".window-content").html('<iframe src ="'+dataFinal[1]+'" width="95%" height="95%"></iframe>');
                                    }
                                    else
                                    {
                                        $toolButton = $window.data("toolButton");
                                        $toolButton.remove();
                                        $window.remove();
                                        window.location.assign(dataFinal[1]);
                                    }
                                }
                                
                            }
                        });  
        }
        else
        {
            $window.children(".window-content").html('<iframe src ="'+options.iframeURL+'" width="95%" height="95%"></iframe>');
        }
    }
    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,
                            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]);
                                        
		                                if(obj.length > 0)
		                                {
		                                    for(i=0; i < obj.length; i++)
		                                    {
		                                        $(obj[i]).find('.window-content').each(function()
		                                        {
		                                            if(this.childNodes.length > 0)
		                                            {
		                                                if(this.childNodes[0].id == objData[0].id)
		                                                {
		                                                    alert('window is already opened');
		                                                    $toolButton = $window.data("toolButton");
                                                            $toolButton.remove();
                                                            $window.remove();
		                                                    return;
		                                                }
		                                            }
		                                        });
		                                    }
		                                }
                                        $window.children(".window-content").html(dataFinal[1]);
                                    }
                                    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(options.domContent.clone(true));
		}
    }
    else 
    {
        $window.children(".window-content").html(options.content);
    }
    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);


