jQuery(function($) {	
	// kview version 1.3
	// -------------------------------------------------------
	// Private Variables
	// -------------------------------------------------------
	var window_padding = 40; //the extra left + right width, compare to the size of the middle wrapper
	var isIE = $.browser.msie;
	
	var kview_ie = 	'<a href="javascript:void(0)" class="kclose_icon kclose">Close</a>'+
					'<div class="kview_Top_Wrapper"><div class="kview_tl_ie"><div class="kview_tr_ie"><div class="kview_t_ie"></div></div></div></div>'+
					'<div class="kview_Mid_Wrapper"><div class="kview_l_ie"><div class="kview_r_ie"><div class="kview_c loading">'+
						'<div id="kview_container" class="kclear"></div>'+
					'</div></div></div></div>'+
					'<div class="kview_Bottom_Wrapper"><div class="kview_bl_ie"><div class="kview_br_ie"><div class="kview_b_ie"></div></div></div></div>';

	var kview = 	'<a href="javascript:void(0)" class="kclose_icon kclose">Close</a>'+
					'<div class="kview_Top_Wrapper"><div class="kview_tl"><div class="kview_tr"><div class="kview_t"></div></div></div></div>'+
					'<div class="kview_Mid_Wrapper"><div class="kview_l"><div class="kview_r"><div class="kview_c loading">'+
						'<div id="kview_container" class="kclear"></div>'+
					'</div></div></div></div>'+
					'<div class="kview_Bottom_Wrapper"><div class="kview_bl"><div class="kview_br"><div class="kview_b"></div></div></div></div>';
		
	// -------------------------------------------------------
	// Public function
	// -------------------------------------------------------
	// jQuery extension function. A paramater object could be used to overwrite the default settings
	$.fn.kview = function(options) {
		var defaults = {
			onStart : function(){}, // Callback when start
			onLoading : function(){},
			onReady : function(){}, // Callback when ready
			onClosing : function(){},
			onClosed : function(){}, // Callback when close
			$wrapper : null,
			$wrapper_top:null,
			$wrapper_center:null,
			$wrapper_bottom:null,
			$bg:null,
			$container:null,
			$closeButton: $('.kclose'), // selector for close a new window
			wrapperZ : 1000, // Window's z-index , should be greater than bgZ (Background z-index)
			bgColor : '#000000', // Background color
			bgOpacity : '0.5', // Background alpha value
			bgZ : 900, // Background z-index
			fading_top: 40, //how far will box drop from top to the center when opening
			fading_bottom : 20, //how far will box drop from cetner to bottom center when closing
			auto_load:false, //set this will make the popup loads up automaticlly after page load
			auto_disable_scroll: false, //automaticlly disable scrolling once kview launched
			auto_center: true, //automaticlly re-center the window upon scrolling or resizing
			escClose: true, //close kview by pressing esc button
			bgClose: true, //close kview by clicking out side of the floating window
			iconClose: true, //close kview by clicking the close icon			
			type: '', // kview type (form, formData, iframe, image, etc...)
			from: '', // Dom object where the call come from
			target: '', // Dom object what is the calling target; eg. <a href="test">Sample</a>; '#test' is the target
			close_selector : '.kclose', //default selector for close a window
			width: 180, // default Width
			height: 150 // default Height
		};
		var settings = $.extend(true, {}, defaults, options);
		
		if (!this)
			return false;
		return this.each(function(){
			if(settings.auto_load){
					processModal($.extend(settings, { from: this }));
					return true;
			}
			if (this.nodeName.toLowerCase() == 'form') {
				$(this).submit(function(e) {
					if ($(this).data('processing'))
						return true;
					if (this.enctype == 'multipart/form-data') {
						processModal($.extend(settings, { from: this }));
						return true;
					}
					e.preventDefault();
					processModal($.extend(settings, { from: this }));
					return false;
				});
			} else {
				$(this).click(function(e) {
					e.preventDefault();
					processModal($.extend(settings, { from: this }));
					return false;
				});
			}
		});
		
	};
	
	// Main function
	function processModal(settings, callback) {
		//Callback : On Start
		settings.onStart.call(this);
		
		//Settings : bind the the opening selector
		//settings.$openButton = $(settings.from);
		
		//Settings : disable the scroll?
		if(settings.auto_disable_scroll){$('html').css('overflow','hidden');}
		
		//Settings : get link's target type
		settings.type = getType(settings);
		
		//if this is an inline call, then no loading animation
		if(settings.type=='inline'){		
			//grab the dimension of the source
			settings.width = $(settings.target).width();
			settings.height = $(settings.target).height();
			
			//load the modal in
			loadModal(settings,function(){
				//Callback : ready
				settings.onReady.call(this);
			});
		}
		
		/*
		showLoading(settings, function(){
			//resize(modal, $.extend(settings, { width:500, height:300 }), function(){
				//show content after resize
				modal.container.fadeIn(300);
			//});
		});
		*/
	};
	
	
	function loadModal(settings, callback) {
		//Assign : the variables for later use
		settings.$wrapper = $('<div class="kview_Wrapper" />');
		
		//Create : the alpha background
		settings.$wrapper.appendTo('body')
			.hide()
			.before('<div id="kviewBg"></div>');
					
		//Create : ie version of window (no shadow) if needed
		if(isIE){			
			settings.$wrapper.append(kview_ie);
		}else{
			settings.$wrapper.append(kview);
		}
		
		//Assign : the other variables for later use
		settings.$bg = $('#kviewBg');
		settings.$container = $('#kview_container');
		settings.$wrapper_top = $('.kview_Top_Wrapper');
		settings.$wrapper_center = $('.kview_c');
		settings.$wrapper_bottom = $('.kview_Bottom_Wrapper');
		
		//Create : content for the newly created kview window
		if (settings.type == "inline"){
		
			//remove loading gif
			$('.kview_c').removeClass('loading');
			
			//load content in stright away
			settings.$container.append($(settings.target).contents());
						
			//assign correct dimension
			assignDimension(settings);
			
			//center the window with an offset to makeup the fading distance
			center(settings, 0, -settings.fading_top);
			
		}else{
			//assign default loading panel size to content area
			//$('.kview_c').css({ 'width':defaultWidth, 'height':defaultHeight});
		}
		
		//bg animation
		settings.$bg.css({'background-color':settings.bgColor, 'z-index':settings.bgZ , 'opacity': settings.bgOpacity}).stop(true).fadeIn(100);
		//window animation
		settings.$wrapper.show().css({'z-index':settings.wrapperZ, 'opacity':0}).stop(true).animate({
				top: '+='+ settings.fading_top +'px',
				opacity: 1
		}, {complete: callback, duration: 500});
		
		//Callback : On Start
		//settings.onLoading.call(this);
		
		//Closing funcitons
		settings.$closeButton.live('click',function(){
			closeModal(settings);
		});
		settings.$bg.live('click',function(){
			if(settings.bgClose){closeModal(settings);}
		});
		$(settings.close_selector).live('click',function(){
			closeModal(settings);
		});
		$(document).keypress(function(e){
			if(e.keyCode==27 & settings.escClose){ closeModal(settings); }
		});
		
		//auto re-center onup resizing/scrolling window
		$(window).bind("resize", function(){
			if(settings.auto_center){center(settings,0,0);}			
		});
		$(window).bind("scroll", function(){
			if(settings.auto_center){center(settings,0,0);}
		});  
		
	};
	
	function closeModal(settings){
		//append content back to where it came from
		settings.$container.contents().appendTo($(settings.target));
		
		//play animation
		settings.$wrapper.stop(true).animate({
				top: '+='+ settings.fading_bottom +'px',
				opacity: 0
		}, function(){
			//release scroll lock
			$('html').css('overflow','auto');
			
			//fae bg out after animation is done
			settings.$bg.stop(true).fadeOut(400);
			
			//and remove the window
			settings.$wrapper.remove();
			
			//Callback : closed
			settings.onClosed.call(this);
		});
			
	};
	
	// -------------------------------------------------------
	// Utilities
	// -------------------------------------------------------
	
	//linked document type: inline, form, ajax etc
	function getType(settings){
		//if link starts with # then it is an inline content
		settings.target = $(settings.from).attr("href");

		if (settings.target.slice(0,1) == "#"){
			return "inline";
		} else {
			return "";
		}
	};
	
	//center the kview window
	function center(settings, offset_x, offset_y){
		settings.$wrapper.css({
			left: getTopX(settings) + offset_x,
			top: getTopY(settings) + offset_y
		});
	};
	
	function getTopX(settings){
		var windowWidth = $(window).width();
		return (windowWidth/2)-(settings.$wrapper.width()/2);
	};
	
	function getTopY(settings){
		var windowHeight = $(window).height();
		return (windowHeight/2)-(settings.$wrapper.height()/2)+document.documentElement.scrollTop;
	};
	
	//assign right dimension to window
	function assignDimension(settings){
		settings.$wrapper_center.css({ 'width':settings.width, 'height':settings.height});
		settings.$wrapper_top.css({'width':settings.width+window_padding});
		settings.$wrapper_bottom.css({'width':settings.width+window_padding});
	};
	
	// -------------------------------------------------------
	// Default initialization
	// -------------------------------------------------------
	//$('.kview').kview();
	
});