/**
 * Cassio Popup - Plugin using jQuery for window.open() replacement.
 * @requires jQuery v1.3.2 or above
 *
 * http://www.darlesson.com/
 *
 * Copyright (c) 2007 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.0
 * Requires Jquery 1.3.2. or superior
 *
 * Call the function
 * <a href=""></a>
 */
 
var cassioPopupSettings = {
	ImagesPath : "/library/cassiopopup/images/"
};

// Popup
(function($){
	$.cassioPopup = function(data){
		var $this = $("a[rel='cassioPopup']");
		$this.each(function(){
			$(this).click(function(){
				//alert("Função ainda em desenvolvimento");
				return false
			});				
		});
	};
	
	$.extend($.cassioPopup, {
			 
		settings: function(){
			
		},
			 
		create: function(settings, $this){
			var href = $this.attr("href");
			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 != null)? settings.Type.toLowerCase():settings.Type;
			var Content = settings.Content;
			var Position = settings.Position;
			var Width = settings.Width;
			var Height = settings.Height;
			var Top = settings.Top.toLowerCase();
			var Left = settings.Left.toLowerCase();
			var Minimize = (settings.Minimize != null && (settings.Minimize == false || settings.Minimize === "false") )? false:true;
			var Maximize = (settings.Maximize != null && (settings.Maximize == false || settings.Maximize === "false") )? false:true;
			var Close = (settings.Close != null && (settings.Close == false || settings.Close === "false") )? false:true;
			var ImagesPath = settings.ImagesPath;
			var HTML = settings.HTML;
			
		// Identify popup Type
			if(Type != "ajax" && Type != "iframe" && Type != "html" && Type != "image" && Type != "slideshow"){
				Type = null;
			};
			if(Type == null){
				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/");
				};
			};
			
		// 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%";
			}
			
			if( isNaN(Width) ){
				if( 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("%") > -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);
			};
			
		// Add the attributes
			HTML = $(HTML) // Id and type
				.attr({
					"id": Name,
					"type": Type
				})
				.css({
					"position": Position,
					"width": Width,
					"height": Height,
					"top": Top,
					"left": Left
				})
			HTML.find(".cp_header")
				.attr("id", Name + "_handle");
			HTML.find(".cp_minimize").html('<img src="' + ImagesPath + 'ico_minimize.gif" />');
			HTML.find(".cp_maximize").html('<img src="' + ImagesPath + 'ico_maximize.gif" />');
			HTML.find(".cp_close").html('<img src="' + ImagesPath + 'ico_close.gif" />');
			if( Title == null ){ // Title
			    HTML.find(".cp_title")
					.css({"display": "none"})
					.addClass("cp_titleEmpty");
			}else{
			    HTML.find(".cp_title").text(Title);
			};
			if( Type == "iframe" ){ // Iframe
				href = (Content != null)? Content:href;
                HTML.find(".cp_content")
                    .html("<iframe id='" + Name + "_iframe' frameborder='0' style='width:100%;' src='" + href + "'></iframe>");
			}else if( Type == "html" && Content != null ){ // HTML
				HTML.find(".cp_content")
					.html(Content);
			}else if( Type == "html" ){
				HTML.find(".cp_content")
					.html($(""+ href).html());
			}
	
		// Minimize popup
			var $minimize = HTML.find(".cp_minimize");
			if( !Minimize ){
				$minimize.css("display", "none");
			};
				
		// Maximize and Restore Popup
			var $maximize = HTML.find(".cp_maximize");
			if( !Maximize ){
				$maximize.css("display", "none");
			}else{
				$maximize.click(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",ImagesPath + "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",ImagesPath + "ico_restore.gif");
					}
				});
			};
					
		// Remove popup
			var $close = HTML.find(".cp_close");
			if( !Close ){
				$close.css("display", "none");
			}else{
				$close.click(function(){
					var $thisRemove = $("#" + Name);
					var zIndex = $thisRemove.css("z-index");
					$thisRemove.remove();	
					$.cassioPopup.Focus(Name, zIndex);
				});
			};
			
			if( !Minimize && !Maximize && !Close ){HTML.find(".cp_controlls").css("display", "none");}
		
		// Append popup
			$("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).innerHeight();
			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 + "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"	 
					});
			};
			
		// Make it draggable
			if( Position == "fixed" ){
				$.cassioPopup.DragDrop(Name, Width, Height, clientWidth, clientHeight, scrollTop, scrollLeft);
			};
		
		// Show Popup
			$("#" + Name).css({
				"display": "block"
				})
				.click(function(){
					$.cassioPopup.Focus(Name);			
				});
				
			$.cassioPopup.Focus(Name);
				
		},
		
		Update : function(settings, $this){
			var href = $this.attr("href");
			
			var Name = settings.Name;
			var $popup = $("#" + Name);
			var Title = settings.Title; 
			var Type = $popup.attr("type");
			var Content = settings.Content;
			var AllowTabs = (settings.AllowTabs == false || settings.AllowTabs.toLowerCase() === "false")? false:true;
			if(Type == "iframe"){
				var $iframe = $("#" + Name + "_iframe");
				href = (Content != null)? Content:href;
				if($iframe.attr("src").indexOf(href) > -1){
					$iframe.attr("src",href);
				}else if(AllowTabs){
					$.cassioPopup.Tabs(settings);
				};
			}else if(Type == "html"){
				var $html = $("#" + Name + " .cp_content");
				Content = (Content == null)? $(""+ href).html():Content;
				$html.html(Content);
			};
			$.cassioPopup.Focus(Name);
		},
		
		Tabs : function(settings){
			var Name = settings.Name;
			var Title = settings.Title;
			var ImagesPath = settings.ImagesPath;
			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='" + ImagesPath + "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){
			var arrPopups = $(".cassioPopup");
			var $popup = $("#" + Name);
			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 + 99999)
						.attr("focus","true");
				}else{
					$popup
						.css("z-index",arrPopups.length + 99999)
						.attr("focus","true")
						.fadeTo("slow",1);
				};
			}else{ // On remove
				var popupName;
				arrPopups.each(function(index){
					var biggestzIndex = 99999; // 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 + 99999)
					.attr("focus","true")
					.fadeTo("slow",1);
			};
		},
		
		DragDrop: function(Name, Width, Height, clientWidth, clientHeight, scrollTop, scrollLeft){

			var scrollY; // Check the existence of scrollbar
			var scrollX;
			scrollY = scrollBar("y"); 
			scrollX = scrollBar("x");
			scrollY = (scrollY)? 10:10;
			scrollX = (scrollX)? 10:10;
		
			var theHandle = document.getElementById(Name +"_handle");
			var theRoot = document.getElementById(Name);
			var dragInit = Drag.init(theHandle, theRoot, 10, ((clientWidth - Width) - scrollY), 10, ((clientHeight - Height) - scrollX));
		}
		
	});
	
	$.fn.cassioPopup = function(options) {
		
	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:400, // Optional (Wrong value will return the default size)
			Height:400, // 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)
			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.
			ImagesPath: (cassioPopupSettings.ImagesPath)? cassioPopupSettings.ImagesPath:"images/",
			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_minimize"></div> \
							<div class="cp_maximize"></div> \
							<div class="cp_close"></div> \
						</div> \
					</div> \
					<div class="cp_content"></div> \
					<div class="cp_footer"></div> \
				</div> \
			</div>'
		},
		settings = $.extend({}, defaults, options);

		this.each(function(){
			var $this = $(this);
			var AllowTabs = (settings.AllowTabs == false || settings.AllowTabs.toLowerCase() === "false")? false:true;

			if($.browser.msie && parseInt($.browser.version) < 7){ // IE6
				settings.Position = "absolute";
			};

			// Call popup
			$this.click(function(){ 
				
				// Check if this popup already exists
				if( $("#" + settings.Name).length > 0 && AllowTabs ){
					$.cassioPopup.Update(settings, $this);
				}else{
					$.cassioPopup.create(settings, $this);
				};
				
				return false										 
			});
			
		});
		return this;
	}
	
})(jQuery);

function scrollBar(scrollXY){
	var scrollLength = (scrollXY.toLowerCase() == "x")? document.getElementsByTagName("body")[0].clientWidth:document.getElementsByTagName("body")[0].clientHeight;
	var clientLength = (scrollXY.toLowerCase() == "x")? document.getElementsByTagName("html")[0].clientWidth:document.getElementsByTagName("html")[0].clientHeight;
	scrollXY = (scrollLength > clientLength)? true:false;
	return scrollXY;
}

/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************/

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper){
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e){
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e){
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function(){		
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e){
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};
