/**
 * Cassio Popup - Plugin using jQuery for window.open() replacement.
 * @requires jQuery v1.3.2 or above
 *
 * http://www.darlesson.com/
 *
 * Copyright (c) 2010 Darlesson Oliveira (www.darlesson.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.1.2
 * Requires Jquery 1.3.2. or superior
 *
 * Call the function
 * <a href=""></a>
 */
 
// Default Settings
$(document).ready(function(){
	//$.cassioPopup.DefaultSettings = {ImgSRC:"/"};
});

// Popup
(function($){
	
	// These are arrays are responsible for the functions that are executed internally by cassioPopup and for the events attribute by the developer 
	var arrOnBeforeCreate = new Array(),
		arrOnCreate = new Array(),
		arrOnBeforeRemove = new Array(),
		arrOnRemove = new Array();
	
	// Starts a new cassioPopup without a selector. It's usefull if you need to call it from a function or if you are unable to define an element to receive the event click
	$.cassioPopup = function(options){
		var settings = $.cassioPopup.Settings(options);
		
		// Check if there is a modal opened
		
		var hasModal = false;
		if( settings.Modal ){
			var arrPopups = $.cassioPopup.Get();
			arrPopups.each(function( index ){
				if( $(this).attr("ismodal") ){
					hasModal = true;
				}
			});
		};
		
		if( !hasModal ){
		
			if(settings.Name == null){ // Create a random name for the new popup. It doesn't allow update
				var randomNumber;
				var booExists = true;
				while(booExists == true){
					randomNumber = $.cassioPopup.RandomName();
					booExists = ( $("#cassiopopup" + randomNumber).length > 0 )? true:false;
					settings.Name = "cassiopopup" + randomNumber;
				}
			};
			
			if( $("#" + settings.Name).length > 0 ){ // Check if this popup already exists
				$.cassioPopup.Update( settings );
			}else{ // Create a popup
				$.cassioPopup.Create( settings );
			};
			
		}
		
	};
	
	$.extend($.cassioPopup, {
			 
		Settings: function(options){
			
			options = $.extend({}, $.cassioPopup.DefaultSettings, options); // Merging the redefined default and the optional settings
			
			var
				defaults = {
					$this:null,
					Name:null, // null=random, string (If two popups are called from the same link with the same name, the popup content it is replaced. If it is called from different links, the new content is opened in the same popup in a tab)
					Title:null, // If the name for the popup is not declared, the title bar will no appear
					Type:null, // Ajax (It must be declared or it will be loaded in Iframe type), Iframe, HTML, Image, Slideshow (It adds pictures' navigation)
					Modal:false, // The website it is not clickable
					Content:null, // Link for type=Ajax, Iframe, Image and Slideshow. HTML for type=HTML
					Position:'fixed', // absolute for position related to the content. fixed for position related to the client sizes
					Width:450, // Optional (Wrong value will return the default size)
					Height:300, // Optional (Wrong value will return the default size)
					Top:'middle', // The options are: top, middle, bottom, a number (this number is related to the top)
					Left:'middle', // The options are: left, middle, right, a number (this number is related to the left)
					WindowOpen:true, // The options are: true or false. This parameter is valid only for Type = "Iframe"
					Minimize:null, // True, False or Null. Null returns True.
					Maximize:null, // True, False or Null. Null returns True.
					Close:null, // True, False or Null. Null returns True.
					AllowTabs:null, // True, False or Null. Null returns True.
					AllowDragAndDrop:null, // True, False or Null. Null returns True.
					ImgSRC:"images/", // Related to the cassioPopup images
					OnBeforeCreate: null, //*******Develop this
					OnCreate: null, // It can receive a function to be executed with the popup creation
					OnBeforeRemove: null, // It can receive a function to be executed before the popup removal
					OnRemove: null, // It can receive a function to be executed with the popup removal
					HTML: '\
					<div class="cassioPopup"> \
						<div class="cp_container"> \
							<div class="cp_header"> \
								<div class="cp_title"></div> \
								<div class="cp_tab"></div> \
								<div class="cp_controlls"> \
									<div class="cp_windowOpen"><img src="images/ico_windowOpen.gif" /></div> \
									<div class="cp_minimize"><img src="images/ico_minimize.gif" /></div> \
									<div class="cp_maximize"><img src="images/ico_maximize.gif" /></div> \
									<div class="cp_close"><img src="images/ico_close.gif" /></div> \
								</div> \
							</div> \
							<div class="cp_content"></div> \
							<div class="cp_footer"></div> \
						</div> \
					</div>'
				},
				settings = $.extend({}, defaults, options); // Mergin the default and the optional settings
		
				settings.Type = (settings.Type != null)? settings.Type.toLowerCase():settings.Type;
				settings.Modal = ( (settings.Modal == true || settings.Modal === "true") )? true:false;
				settings.Top = settings.Top.toLowerCase();
				settings.Left = settings.Left.toLowerCase();
				settings.WindowOpen = ( (settings.WindowOpen == false || settings.WindowOpen === "false") )? false:true;
				settings.Minimize = (settings.Minimize != null && (settings.Minimize == false || settings.Minimize === "false") )? false:true;
				settings.Maximize = (settings.Maximize != null && (settings.Maximize == false || settings.Maximize === "false") )? false:true;
				settings.Close = (settings.Close != null && (settings.Close == false || settings.Close === "false") )? false:true;
				settings.AllowDragAndDrop = ((!settings.Modal) || (settings.AllowDragAndDrop == null && !settings.Modal) || (settings.AllowDragAndDrop == true || settings.AllowDragAndDrop === "true") )? true:false;
				settings.OnBeforeCreate = ( $.isFunction( settings.OnBeforeCreate ) )? settings.OnBeforeCreate:( settings.OnBeforeCreate == null )? null:false;
				settings.OnCreate = ( $.isFunction( settings.OnCreate ) )? settings.OnCreate:( settings.OnCreate == null )? null:false;
				settings.OnBeforeRemove = ( $.isFunction( settings.OnBeforeRemove ) )? settings.OnBeforeRemove:( settings.OnBeforeRemove == null )? null:false;
				settings.OnRemove = ( $.isFunction( settings.OnRemove ) )? settings.OnRemove:( settings.OnRemove == null )? null:false;
				
				return settings
		},
			 
		Create: function(settings, $this){
			
			// Add cassioPopup special events to their array
			arrOnBeforeCreate.push( settings.OnBeforeCreate );
			arrOnCreate.push( settings.OnCreate );
			arrOnBeforeRemove.push( settings.OnBeforeRemove );
			arrOnRemove.push( settings.OnRemove )
			
			var $body = $("body");
			if( $body.length == 0 ){
				$.cassioPopup.Log( "cassioPopup needs proper HTML formatting. Tags <html>, <head> and <body> are necessary." );	
				return false	
			}else if( $body.attr("handlingbodyresize") == undefined ){ // It applies proper behaviour for the popups when the window is resized
				$.cassioPopup.HandlingBodyResize();
			};
			
			var hasSelector = ( $this != undefined )? true:false; // It returns false when the selector doesn't have a selector
			var href = ( hasSelector )? ( (settings.Content != null)? settings.Content:$this.attr("href") ):settings.Content;
			var HateIE = (document.all)? true:false; // I hate Internet Explorer
			var booThisExist = false;
			var arrImageExtensions = [".JPEG",".JPG",".PNG",".GIF"];
			var arrConsole = new Array();
			
			var Name = settings.Name;
			var Title = settings.Title; 
			var Type = settings.Type;
			var Modal = settings.Modal;
			var Content = settings.Content;
			var Position = ($.cassioPopup.IE6())? "absolute":settings.Position;
			var Width = settings.Width;
			var Height = settings.Height;
			var Top = settings.Top;
			var Left = settings.Left;
			var WindowOpen = settings.WindowOpen;
			var Minimize = settings.Minimize;
			var Maximize = settings.Maximize;
			var Close = settings.Close;
			// Programar
			var AllowTabs = settings.AllowTabs; // True, False or Null. Null returns True.
			var AllowDragAndDrop = settings.AllowDragAndDrop; // True, False or Null. Null returns True.
			var ImgSRC = settings.ImgSRC;
			var HTML = settings.HTML;
			
			//$("#recebe").html("Minimize: " + Minimize + ", Maximize: " + Maximize + ", Close: " + Close)
			
		// Identify popup Type
			if( Type != "ajax" && Type != "iframe" && Type != "html" && Type != "image" && Type != "slideshow" ){
				Type = null;
			};
			if( Type == null && hasSelector ){
				var booImage = null;
				for(var x = 0; x < arrImageExtensions.length; x++){
					if( href.substring(href.lastIndexOf("."),href.length).toUpperCase() == arrImageExtensions[x] ){
						booImage = true;
						break
					};
				};
				if( $("" + href).length > 0 ){ Type = "html";
				}else if( booImage ){
					Type = "image";
				}else if( href != "#" && href.indexOf("javascript:") == -1 ){ Type = "iframe";
				}else{ console.log("%s: %o. Please check the documentation in %o", "cassioPopup Type attribute declaration could no be defined or recognized", this, "http://www.darlesson.com/");
				};
			};
			if( Type == "image" ){
				Content = href;
			};
			
		// Define Width and Height
			var documentPadding = 10;
			var scrollTop = $(document).scrollTop();
			var scrollLeft = $(document).scrollLeft();
			var scrollHeight = $(document).height();
			var scrollWidth = $(document).width();
			var clientHeight = $body.outerHeight();
			var clientWidth = $body.outerWidth();
			
			/*
			var scrollHeight = document.getElementsByTagName("body")[0].clientHeight;
			var scrollWidth = document.getElementsByTagName("body")[0].clientWidth;
			var clientHeight = document.getElementsByTagName("html")[0].clientHeight;
			var clientWidth = document.getElementsByTagName("html")[0].clientWidth;
			var scrollTop = document.getElementsByTagName("html")[0].scrollTop;
			var scrollLeft = document.getElementsByTagName("html")[0].scrollLeft;
			*/
			if( !isNaN(Width) && (Width > clientWidth) ){
				Width = "100%";
			}
			if( !isNaN(Height) && (Height > clientHeight) ){
				Height = "100%";
			}
			var isMaximized = (Width == "100%" && Height == "100%")? true:false; 
			
			if( isNaN(Width) ){
				if( Width.lastIndexOf("px") > -1 ){
					Width = Width.substring(0, Width.lastIndexOf("px"));
					Width = (parseInt(Width) > clientWidth)? "100%":parseInt(Width);
				}
				if( isNaN(Width) && Width.lastIndexOf("%") > -1 ){
					Width = Width.substring(0, Width.lastIndexOf("%"));
					Width = (parseInt(Width) > 100)? 100:parseInt(Width);
					Width = ((clientWidth * Width) / 100) - (documentPadding * 2);
				}
			}
			if( isNaN(Height) ){
				if( Height.lastIndexOf("px") > -1 ){
					Height = Height.substring(0, Height.lastIndexOf("px"));
					Height = (parseInt(Height) > clientHeight)? "100%":parseInt(Height);
				}
				if( isNaN(Height) && Height.lastIndexOf("%") > -1 ){
					Height = Height.substring(0, Height.lastIndexOf("%"));
					Height = (parseInt(Height) > 100)? 100:parseInt(Height);
					Height = ((clientHeight * Height) / 100) - (documentPadding * 2);
				}
			}
			
		// Calculate Top and Left			
			if( Top === "top" ){ Top = (Position === "fixed")? documentPadding:scrollTop + documentPadding;
			}else if( Top === "bottom" ){ Top = ((( Position === "fixed" )? 0:scrollTop) + (clientHeight)) - Height - documentPadding;
			}else{ Top = ((clientHeight - Height) / 2) + (( Position === "fixed" )? 0:scrollTop);
			};
			
			if( Left === "left" ){ Left = (Position === "fixed")? documentPadding:scrollLeft + documentPadding;
			}else if( Left === "right" ){ Left = ((( Position === "fixed" )? 0:scrollLeft) + (clientWidth)) - Width - documentPadding;
			}else{ Left = ((clientWidth - Width) / 2) + (( Position === "fixed" )? 0:scrollLeft);
			};
			
		// Define variables for the elements
			HTML = $(HTML);
			var $header = HTML.find(".cp_header");
			var $title = HTML.find(".cp_title");
			var $content = HTML.find(".cp_content");
			var $controlls = HTML.find(".cp_controlls");
			var $windowOpen = HTML.find(".cp_windowOpen");
			var $minimize = HTML.find(".cp_minimize");
			var $maximize = HTML.find(".cp_maximize");
			var $close = HTML.find(".cp_close");
			
		// Add the attributes
			HTML
				.attr({
					"id": Name,
					"type": Type,
					"isModal": Modal
				})
				.css({
					"position": Position,
					"width": Width,
					"height": Height,
					"top": Top,
					"left": Left
				})
			
			$header
				.attr("id", Name + "_handle");
			if( Title == null ){
			    $title
					.css({"display": "none"})
					.addClass("cp_titleEmpty");
			}else{
			    $title.text(Title);
			};
		
		// Type : Modal
			if( Modal ){
				var HTMLModal = "<div id='" + Name + "_modalBG' style='height:" + clientHeight + "px; width:" + clientWidth + "px; z-index:2147483646;' class='cp_modalBg'></div>";
			};
		
		// Type : Ajax
			if( Type == "ajax" ){
				$.cassioPopup.Ajax(Name, href);
			};

		// Type : Iframe
			if( Type == "iframe" ){
				href = (Content != null)? Content:href;
                $content
                    .html("<iframe onload='$.cassioPopup.ApplyFunctionRemove(\"" + Name + "_iframe\", \"iframe\");' id='" + Name + "_iframe' frameborder='0' style='width:100%;' src='" + href + "'></iframe>"); // Incluir onload
		
		// Type : HTML
			}else if( Type == "html" && Content != null ){
				$content
					.html(Content);
			}else if( Type == "html" ){
				$content
					.html($(""+ href).html());
			
		// Type : Image
			}else if( Type == "image" ){
				$content
					.html("<img src='" + Content + "' alt='' />");
			}
		
		// Switch to window.open()
			if( Type != "iframe" || Modal == true ){
				$windowOpen.remove();
			}else{
				$windowOpen.click(function(){
					//if() Check if the popup is already open and cancel the creatino of a new popup
					//Get the sizes
										   
					var features = "width=" + Width + ", height=" + Height + ", top=" + Top + ", left=" + Left;
					var cassioPopupToWindowOpen = window.open( href, Name, features);
					
					alert(cassioPopupToWindowOpen.closed)
					
					if( window.focus ){
						cassioPopupToWindowOpen.focus();
					};
					$.cassioPopup.Remove( Name );
				});
			};
	
		// Minimize popup
			if( !Minimize ){
				$minimize.css("display", "none");
			//}else if( isMaximized ){
			}else{
				$minimize.find("img").attr("src",ImgSRC + "ico_minimize.gif");
				$minimize.click(function(){
					//if(){  // Restore
					//}else{ // Minimize
						 
					//}
				});
			};
				
		// Maximize and Restore Popup
			if( !Maximize || isMaximized ){
				$maximize.css("display", "none");
			}else{
				$maximize.find("img").attr("src",ImgSRC + "ico_maximize.gif");
				
				$.cassioPopup.EventToHandler([{evt : "dblclick", selector : $title}, {evt : "click", selector : $maximize}], function(){
					var $thisPopup = $("#" + Name + "");
					var $thisContainer = $thisPopup.find(".cp_container");
					var $thisContent = $thisPopup.find(".cp_content");
					var $thisIframe = $("#" + Name + "_iframe");
					if( $thisPopup.attr("maximized") === "true" ){ // Restore
						$thisPopup.attr("style", $thisPopup.attr("styleHistory"));
						$thisContainer.attr("style", $thisContainer.attr("styleHistory"));
						$thisContent.attr("style", $thisContent.attr("styleHistory"));
						$thisIframe.attr("style", $thisIframe.attr("styleHistory"));
						$maximize.find("img").attr("src",ImgSRC + "ico_maximize.gif");
						$thisPopup.attr("maximized","false");
					}else{ // Maximize
						var position = $thisPopup.css("position");
						var popupHeight = $thisPopup.css("height");
						popupHeight = parseInt(popupHeight.substring(0,popupHeight.lastIndexOf("px")));
						var contentHeight = $thisContent.css("height");
						contentHeight = parseInt(contentHeight.substring(0,contentHeight.lastIndexOf("px")));
						var containerHeight = $thisContainer.css("height");
						containerHeight = parseInt(containerHeight.substring(0,containerHeight.lastIndexOf("px")));
						scrollTop = (position == "fixed")? 0:scrollTop;
						scrollLeft = (position == "fixed")? 0:scrollLeft;
						$thisPopup
							.attr({
								"styleHistory": $thisPopup.attr("style"),
								"maximized": "true"
							})
							.css({
								"width": (clientWidth - (documentPadding * 2)) + "px",
								"height": (clientHeight - (documentPadding * 2)) + "px",
								"top": scrollTop + documentPadding + "px",
								"left": scrollLeft + documentPadding + "px"
							});
						$thisContainer
							.attr("styleHistory", $thisContainer.attr("style"))
							.css("height", containerHeight + ((clientHeight - (documentPadding * 2)) - popupHeight) + "px");
						$thisContent
							.attr("styleHistory", $thisContent.attr("style"))
							.css("height", contentHeight + ((clientHeight - (documentPadding * 2)) - popupHeight) + "px");
						if( $thisIframe.length > 0 ){
							$thisIframe
								.attr("styleHistory", $thisIframe.attr("style"))
								.css("height", (contentHeight - 13) + ((clientHeight - (documentPadding * 2)) - popupHeight) + "px");
						};
						$maximize.find("img").attr("src",ImgSRC + "ico_restore.gif");
					};																												  
				});
			};
					
		// Remove popup
			if( !Close ){
				$close.css("display", "none");
			}else{
				$close.find("img").attr("src",ImgSRC + "ico_close.gif");
				$close.click(function(){
					$.cassioPopup.Remove( Name );
				});
			};
		
		// Don't exhibit controll tag if none of its buttons are available
			if( !WindowOpen && !Minimize && !Maximize && !Close ){$controlls.css("display", "none");}
			
		// Call OnBeforeCreate
			$.cassioPopup.OnBeforeCreate();
			
		// Append popup
			if( Modal ){
				$body.append(HTMLModal);
				if( Close ){
					arrOnCreate.push(
						function(){
							$(document).keydown(function(e){
								if( e.keyCode == 27 ){
									$.cassioPopup.Remove( "#" + Name );
								};
							});
						});
				};
			};
			$body.append(HTML);
			
			var marginTop = $("#" + Name +" .cp_container").css("margin-top");
			var marginBottom = $("#" + Name +" .cp_container").css("margin-bottom");
			marginTop = parseInt(marginTop.substring(0, marginTop.lastIndexOf("px")));
			marginBottom = parseInt(marginBottom.substring(0, marginBottom.lastIndexOf("px")));
			var marginHeightTotal = marginTop + marginBottom;
			var border = $("#" + Name).outerHeight() - $("#" + Name).outerHeight();
			var cp_containerHeight = (Height - marginHeightTotal) - border;
			var cp_titleHeight = $("#" + Name +" .cp_title").css("height");
			cp_titleHeight = parseInt(cp_titleHeight.substring(0, cp_titleHeight.lastIndexOf("px")));
			var cp_contentHeight = cp_containerHeight - cp_titleHeight;
			$("#" + Name +" .cp_container")
				.css({
					"height": cp_containerHeight + "px"
				})
				.find(".cp_content")
					.css({
						"height": (cp_contentHeight - ((Type == "ajax")? 13:0) ) + "px",
						"margin-top": (( Title == null )? cp_titleHeight:0) + "px"
					});
			if( $("#" + Name +" .cp_content iframe").length > 0 ){
				$("#" + Name +" .cp_content iframe")
					.css({
						"height": (cp_contentHeight - 13) + "px"	 
					});
			};
		
		// Remove attribute
			if( Type === "html" ){
				$.cassioPopup.ApplyFunctionRemove( Name, "html" );
			};
		
		// Show popup
			var $popup = $("#" + Name);
			$popup
				.show()
				.click(function(){
					$.cassioPopup.Focus(Name, null, Modal);			
				});
				
			$.cassioPopup.Focus(Name, null, Modal);
			
		// Make it draggable
			if( Position == "fixed" && !Modal || AllowDragAndDrop ){
				$.cassioPopup.DragDrop( Name, documentPadding );
			};
			
		},
		
		WindowOpen : function( href, Name, features ){
			var $popup = $("#" + Name);
			window.open( href, Name, features );
		},
		
		IE6 : function(){
			return ($.browser.msie && $.browser.version == "6.0")? true:false;
		},
		
		Get : function( selector ){ // Returns the array of objects popup
			var $popup = $(".cassioPopup");
			if( typeof selector === "string" ){
				$popup = $(selector);
				if( $popup.attr(".cassioPopup") == undefined ){
					$popup = null;
				}
			}
			return $popup;
		},
		
		OnBeforeCreate : function(){
		// Execute OnBeforeCreate before "Append popup"
			for(var x = 0; x < arrOnBeforeCreate.length; x++){
				if( arrOnBeforeCreate[x] == false ){
					$.cassioPopup.Log( "OnBeforeCreate must contain a function. Try to wrap your code in OnBeforeCreate: function(){ // Your code in here }" );	
				}else if( arrOnBeforeCreate[x] != null ){
					$( arrOnBeforeCreate[x] );
				};				  
			};
		},
		
		OnCreate : function(){
		// Execute OnCreate. Types iframe and ajax are exceuted in .ApplyFunctionRemove(). Type Ajax is executed in .Ajax
			for(var x = 0; x < arrOnCreate.length; x++){
				if( arrOnCreate[x] == false ){
					$.cassioPopup.Log( "OnCreate must contain a function. Try to wrap your code in OnCreate: function(){ // Your code in here }" );	
				}else if( arrOnCreate[x] != null ){
					$( arrOnCreate[x] );
				};				  
			};
		},
		
		OnBeforeRemove : function(){
		// Execute OnBeforeRemove. Types iframe and ajax are exceuted in .Remove().
			for(var x = 0; x < arrOnBeforeRemove.length; x++){
				if( arrOnBeforeRemove[x] == false ){
					$.cassioPopup.Log( "OnBeforeRemove must contain a function. Try to wrap your code in OnBeforeRemove: function(){ // Your code in here }" );	
				}else if( arrOnBeforeRemove[x] != null ){
					$( arrOnBeforeRemove[x] );
				};
				if( x == arrOnBeforeRemove.length - 1 ){
					return true
				};
			};
		},
		
		OnRemove : function(){
		// Execute OnRemove. Types iframe and ajax are exceuted in .Remove().
			for(var x = 0; x < arrOnRemove.length; x++){
				if( arrOnRemove[x] == false ){
					$.cassioPopup.Log( "OnRemove must contain a function. Try to wrap your code in OnRemove: function(){ // Your code in here }" );	
				}else if( arrOnRemove[x] != null ){
					$( arrOnRemove[x] );
				};
			};
		},
		
		RandomName : function(){
			var randomNumber = Math.random()*(1000-1);
			randomNumber = Math.round(1+randomNumber);
			return randomNumber;
		},
		
		Ajax : function(Name, href ){
			$.ajax({
				type: "GET",
				url: href,
				dataType: "html",
				cache: false,
				success: function(data){
					var HTML = data;
					var $content = $("#" + Name).find(".cp_content");
					$content.html(HTML);
					$.cassioPopup.ApplyFunctionRemove( Name, "ajax" );
				},
				error: function(xhr, ajaxOptions, thrownError){
					alert(thrownError);
				}
			});
		},
		
		EventToHandler : function(bind, data){ // It defines different events to different handlers for the same action
			for(var x = 0; x < bind.length; x++){
				var binder = bind[x];
				binder.selector.bind( binder.evt, data );
			};
		},
		
		Log : function( message ){
			try{
				console.log( message );
				return this;
			}catch(e){};
		},
		
		HandlingBodyResize : function(){
			var $window = $(window);
			$window.resize(function(){
				var $body = $("body");
				var clientHeight = $body.outerHeight();
				var clientWidth = $body.outerWidth();
				var $modal = $(".cp_modalBg");
				$modal.css({
						"height": clientHeight + "px",
						"width": clientWidth + "px"
					});
			});
		},
		
		Remove : function( object ){
			var $popup = $(object);
			if( typeof object === "string" ){
				$popup = ( $(object).length > 0 )? $(object):$("#" + object) ;	
			};
			if( $popup.hasClass("cassioPopup") == false ){
				$popup = $popup.parents(".cassioPopup");
			};
			if( $.cassioPopup.OnBeforeRemove() ){
				
				if( $popup.length > 0 ){
					var zIndex = $popup.css("z-index");
					var isModal = $popup.attr("isModal");
					var Name = $popup.attr("id");
					$popup.remove();
					$.cassioPopup.OnRemove();
					$.cassioPopup.Focus(Name, zIndex, isModal);
					
					if( isModal ){
						var $modal =  $("#" + $popup.attr("id") +"_modalBG");
						$modal.fadeOut();
						window.setTimeout(function(){
							$modal.remove();
						},500);
					};
					
				}else{
					$.cassioPopup.Log( "Failure in remove a cassioPopup. Reference not found." );	
				};
			
			};
		},
		
		ApplyFunctionRemove : function( Name, Type ){ // Writes a JavaScript function to the HTML in iframes to remove cassioPopup when it is called
			// For ajax and HTML
			if( Type === "ajax" || Type === "html" ){
				var $closeCassioPopup = $("#" + Name).find("*[closeCassioPopup]");
				$closeCassioPopup.click(function(){
					var $this = $(this);
					if( $this.attr("closeCassioPopup") == "true" ){
						$.cassioPopup.Remove( this );
					};
					return false
				});
			// For iframes
			}else if( Type === "iframe" ){
				try{
					var $iframe = document.getElementById( Name );
					$iframe = ($iframe.contentWindow)? $iframe.contentWindow : ($iframe.contentDocument.document)? $iframe.contentDocument.document : $iframe.contentDocument;
					
					var $headTag = $iframe.document.getElementsByTagName("head")[0];
					var $bodyTag = $iframe.document.getElementsByTagName("body")[0];
					var $scriptTag = $iframe.document.createElement("script");
					$scriptTag.setAttribute("type","text/javascript");
					var script  = "function closeCassioPopup(){ \
										window.parent.$.cassioPopup.Remove('" + Name + "'); \
									};";
					( $.browser.msie )? ( $scriptTag.text = script ):( $scriptTag.innerHTML = script );
					$headTag.appendChild( $scriptTag );
					
					if( $bodyTag.getAttribute("closecassiopopup") && $bodyTag.getAttribute("closecassiopopup") == "true" ){
						$.cassioPopup.Remove( Name );
					};
				}catch(e){
					$.cassioPopup.Log( "Failure in write closeCassioPopup() in the iframe '" + Name + "' HTML. Permission is usually denied for different website's addresses. Tags <head> and <body> are essential." );	
				};
			};
			$.cassioPopup.OnCreate();
		},
		
		Update : function(settings, $this){
			var hasSelector = ( $this != undefined )? true:false; // It returns false when the selector doesn't have a selector
			var href = ( hasSelector )? $this.attr("href"):settings.Content;
			
			var Name = settings.Name;
			var $popup = $("#" + Name);
			var Title = settings.Title; 
			var Type = $popup.attr("type");
			var Content = settings.Content;
			if(Type == "iframe"){
				var $iframe = $("#" + Name + "_iframe");
				href = (Content != null)? Content:href;
				if($iframe.attr("src").indexOf(href) > -1){
					$iframe.attr("src",href);
				}else{
					$.cassioPopup.Tabs(settings);
				};
			}else if(Type == "html"){
				var $html = $("#" + Name + " .cp_content");
				Content = (Content == null)? $(""+ href).html():Content;
				$html.html(Content);
			};
			$.cassioPopup.Focus(Name, null, false);
		},
		
		Tabs : function(settings){
			var Name = settings.Name;
			var Title = settings.Title;
			var ImgSRC = settings.ImgSRC;
			var $popup = $("#" + Name);
			var $header = $popup.find(".cp_header");
			var $title = $popup.find(".cp_title");
			var $tab = $popup.find(".cp_tab");
			var $container = $popup.find(".cp_container");
			var $content = $popup.find(".cp_content");
			var $iframe = $("#" + Name + "_iframe");
			var closeTab = "<div><img alt='' src='" + ImgSRC + "ico_tab_close.gif' /></div>"
			$header.css("height",$header.height() + 30);
			$content.css("height",$content.height() - 30);
			$iframe.css("height",$iframe.height() - 30)
			// Improve the sizes' controll **********************************************************************
			if( $tab.find("ul").length == 0 ){ // Create the first two tabs
				var html = "<li>" + $title.text() + closeTab + "</li>";
				html += "<li class='selected'>" + Title + closeTab + "</li>";
				$tab.append("<ul>" + html + "</ul>");
				$content.after("<div class='cp_content'>Hello World</div>");
			};
			$.cassioPopup.ControllTabs(Name);
		},
		
		ControllTabs : function(Name){
			var $popup = $("#" + Name);
			var $tabs = $popup.find(".cp_tab");
			var $content = $popup.find(".cp_content");
			$content.css("display","none");
			$tabs.find("li").each(function(index){
				var $this = $(this);
				if( $this.attr("class") == "selected" ){
					$popup.find(".cp_content:eq(" + index + ")").show();
				}else{
					$this.click(function(){
						$tabs.find("li[class='selected']").removeClass("selected");
						$(this).addClass("selected");
						$.cassioPopup.ControllTabs(Name);
					});
				};
			});
			
			
			//var index = $tabs.index(this);
			
		},
		
		Focus : function(Name, zIndex, Modal){
			var arrPopups = $(".cassioPopup");
			var $popup = $("#" + Name);
			if( Modal ){
				$popup.css("z-index", "2147483647"); 
			}else{
				if($popup.attr("focus") != "true" && zIndex == null){ // On append and onClick
					arrPopups.each(function(){
						var $thisPopup = $(this);
						if($thisPopup.css("z-index") > $popup.css("z-index")){
							$thisPopup
								.css("z-index",$thisPopup.css("z-index") - 1)
								.attr("focus","false")
								.fadeTo("slow",0.90);
						}else if($thisPopup.attr("id") != Name){
							$thisPopup
								.attr("focus","false")
								.fadeTo("slow",0.90);
						};
					});
					if($popup.attr("focus") != "false"){
						$popup
							.css("z-index",arrPopups.length + 9999)
							.attr("focus","true");
					}else{
						$popup
							.css("z-index",arrPopups.length + 9999)
							.attr("focus","true")
							.fadeTo("slow",1);
					};
				}else{ // On remove
					var popupName;
					arrPopups.each(function(index){
						var biggestzIndex = 9999; // Catch the biggest z-index to focus
						var $thisPopup = $(this);
						if($thisPopup.css("z-index") > biggestzIndex){
							biggestzIndex = $thisPopup.css("z-index");
							popupName = $thisPopup.attr("id");
						};
					});
					arrPopups.each(function(index){
						var $thisPopup = $(this);
						if($thisPopup.css("z-index") > $("#" + popupName).css("z-index")){
							$thisPopup
								.css("z-index",$thisPopup.css("z-index") - 1)
								.attr("focus","false")
								.fadeTo("slow",0.90);
						}
					});
					$("#" + popupName)
						.css("z-index",arrPopups.length + 9999)
						.attr("focus","true")
						.fadeTo("slow",1);
				};
			};
		},
		
		Drag: function( Name, mousePopupX, mousePopupY, documentPadding ){
			var $body = $("body");
			var $popup = $("#" + Name);
			var $header = $("#" + Name + "_handle");
			
			var Position = $popup.css("position");
			
			var Width = $popup.outerWidth();
			var Height = $popup.outerHeight();
			var clientHeight = $body.outerHeight();
			var clientWidth = $body.outerWidth();
			var scrollTop = $(document).scrollTop();
			var scrollLeft = $(document).scrollLeft();
			
			$body.mousemove(function(e){
				var scrollTop = $(document).scrollTop();
				var scrollLeft = $(document).scrollLeft();
				var scrollHeight = $(document).height();
				var scrollWidth = $(document).width();
				var clientHeight = $body.outerHeight();
				var clientWidth = $body.outerWidth();
									 
				var mouseBodyX = e.pageX;
				var mouseBodyY = e.pageY;
								
				Top = ( mouseBodyY - mousePopupY - ((Position == "fixed")? scrollTop:0 ) );
				Left = ( mouseBodyX - mousePopupX - ((Position == "fixed")? scrollLeft:0 ) );
				
				Top = (Top <= documentPadding)? documentPadding:Top; // Defines margin on the top
				Left = (Left <= documentPadding)? documentPadding:Left; // Defines margin on the left
				
				Top = ( (Top + Height) >= (clientHeight - documentPadding) )? clientHeight - ( Height + documentPadding ):Top; // Defines margin on the bottom
				Left = ( (Left + Width) >= (clientWidth - documentPadding) )? clientWidth - ( Width + documentPadding ):Left; // Defines margin on the right
								
				$popup.css({
						"top": Top + "px",
						"left": Left + "px"
					});
			
			});
		},
		
		DragDrop: function( Name, documentPadding ){
			
			var $body = $("body");
			var $popup = $("#" + Name);
			var $header = $("#" + Name + "_handle");
			
			$header.mousedown(function( e ){ // Define the handler
				var offset = $popup.offset();
				var mousePopupX = Math.round(e.pageX - offset.left);
				var mousePopupY = Math.round(e.pageY - offset.top);
				$.cassioPopup.Drag( Name, mousePopupX, mousePopupY, documentPadding ); // Drag
				document.onselectstart = function(){ return false };
				return false
			});
			
			$header.mouseup(function(){ // Drop
				$body.unbind("mousemove");
				document.onselectstart = function(){ return true };
			});

		}
		
	});
	
	$.fn.cassioPopup = function(options){

		this.each(function(){
		    var $this = $(this);
			
			var settings = $.cassioPopup.Settings(options);
			
		    if( $this.attr("cpattributed") === undefined || $this.attr("cpattributed") === "undefined" ){ // It prevents cassioPopup to attribute 2 or more events to an element
			
		        $this.attr("cpattributed", "true");

		        // Call popup
		        $this.click(function(){
									 
					// Check if there is a modal opened
					var hasModal = false;
					if( settings.Modal ){
						var arrPopups = $.cassioPopup.Get();
						arrPopups.each(function( index ){
							if( $(this).attr("ismodal") ){
								hasModal = true;
							}
						});
					};

			 		if( !hasModal ){
						if( $("#" + settings.Name).length > 0 ){ // Check if this popup already exists
							$.cassioPopup.Update( settings, $this );
						}else{ // Create a popup
							$.cassioPopup.Create( settings, $this );
						};
					}

		            return false
		        });

		    };

		});
		return this;
	}
	
})(jQuery);

/*
AllowDragAndDrop
Success

1-Resolver get and post
2-OnRemove
3-Minimize
4-Abrir no Window.open
5-Bloquear mais de um modal - Ok
6-Ao abrir um novo popup, fechar o modal
7-Permitir title inline
8-Drag on iframe
9-Array de popups length - Ok
10-Verificar a chamada do OnCreate dentro do Onload de popups com iframe
11-Position no IE6
12-ESC remove o popup - Ok

*/
