;(function($) {
/**
 * 获得页面滚动高度 return array x+y
 */
	var getPageScroll = function () {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}
		arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};
/**
 * 获得页面大小 x+y
 */
	var getPageSize = function(){
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};
/**
 *  遮罩层
 */
	jQuery.overLayer = function(options) {
		var jQueryMatchedObj = this;
		var randString = 'overlayer_'+roundString(6);
		$.closeLayer = function (){finish()};
		var defaults = {
				opt:'0.5',
				zindex:'999800',
				color:'#343434'
			};
		var options = $.extend(defaults,options);
		function _initialize() {
			_start(this,jQueryMatchedObj); 
			return false; 
		}
		function _start(objClicked,jQueryMatchedObj) {
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			try{
				var obj = getIFrameDoc('right_frame');
				$(obj).find('embed, object, select').css({ 'visibility' : 'hidden' });
			}catch(e){
					
				}
			_set_interface();
		}
		function _set_interface() {
			$('body').append('<div class="jquery-overlay" style="position: absolute;top: 0;left: 0;z-index:'+options.zindex+';width: 100%;height: 500px;">');	
			$(".jquery-overlay").attr('id',randString);
			var arrPageSizes = getPageSize();
			$('.jquery-overlay').css({
				backgroundColor:	options.color,
				opacity:			options.opt,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			var arrPageScroll = getPageScroll();
			$('.jquery-overlay').click(function() {
			//	_finish();									
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				var arrPageSizes = getPageSize();
				$('.jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
			});
		}
		function finish() {
			$('#'+randString).fadeOut(function() { $(this).remove(); })
			//$('.jquery-overlay').fadeOut(function() { $('.jquery-overlay').remove(); });
			$('embed, object, select').css({ 'visibility' : 'visible' });
			try{
				var obj = getIFrameDoc('right_frame');
				$(obj).find('embed, object, select').css({ 'visibility' : 'visible' });
			}catch(e){}
		}
	function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }while ( curDate - date < ms);
	};
		//return this.unbind('click').click(_initialize);
	//end overLayer
		return _initialize();
};//overLayer
/**
http://www.socialembedded.com/labs/jQuery-Windows-Engine-Plugin/jQuery-Windows-Engine-Plugin.html
http://www.socialembedded.com/labs/jQuery-Windows-Engine-Plugin/jQuery-Windows-Engine-Plugin-v0.6.rar
*/
/*js获得随机字符串 len需要获得的长度*/
function roundString (len){
		var str =  ['a','b','c','d','e','f','h','j','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
		var hash = '';
		for(i=0;i<len;i++){
			var r = str[Math.ceil(Math.random()*100)];
			if(r!=undefined)hash +=r;
		}
		if(hash.length<len)hash+=roundString(len-hash.length);
		return hash;
}
//new window
var jqWindowsEngineZIndex = 999999; 
$.fn.newWindow = function(options){
    var lastMouseX = 0;
    var lastMouseY = 0;
    var defaults = {
		ZIndex :'999999',
        windowTitle : "",
		loadingImg : '',//images/windows_loading.gif
		content: "",
		ajaxURL: "",
        width : 250,
        height : 250,
        posx : 150,//默认左宽度
        posy : 30,//默认定上高度
		onDragBegin: null,
		onDragEnd: null,
		onResizeBegin: null,
		onResizeEnd: null,
		onAjaxContentLoaded: null,
        statusBar: true,
		minimizeButton: false,
		minimizeIcon: " ",
		maximizeButton: true,
		maximizeIcon: "",
		closeButton: true,
		closeIcon: " ",
		draggable: true,//拖拽 有bug
		resizeable: true,//拉大缩小
		resizeIcon: "&nbsp;",//
		windowType: "standard",//调用数据类型
		closeAction:'',//add by 
		closeActionParam:null,//add by 
		appendContent:'',
		showLayer:false// 是否显示遮罩层
    };
	var roundStrings = roundString(10);
    var p_size = getPageSize();
    var x = p_size[0];
    var y = p_size[1];
    var w = window.screen.availHeight;
    var r_y;
    r_y = y>w?w:y;
    var options = $.extend(defaults, options);
    if( options.posx=='0')	options.posx=parseInt((x/3)-150);//设置高度
    if(options.posy =='0')  options.posy=parseInt((r_y/4)-100);
    $windowContainer = $('<div class="window-container"></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>');
	if(options.windowType=="video" || options.windowType=="iframe")
	  $windowContent.css("overflow","hidden");
	var setFocus = function($obj){
	    //$obj.css("z-index",jqWindowsEngineZIndex++);
		 $obj.css("z-index",options.ZIndex++);
	}
	var resize = function($obj, width, height){
		width = parseInt(width);
		height = parseInt(height);
		$obj.attr("lastWidth",width)
		    .attr("lastHeight",height);
		width = width+"px";
		height = height+"px";
		//$obj.css({"width":width,'z-index':jqWindowsEngineZIndex+100})
		$obj.css({"width":width,'z-index':options.ZIndex+100})
	        .css("height", height);
		if(options.windowType=="video"){
		  $obj.children(".window-content").children("embed").css("width", width)
	               .css("height", height);
		  $obj.children(".window-content").children("object").css("width", width)
	               .css("height", height);
		  $obj.children(".window-content").children().children("embed").css("width", width)
	               .css("height", height);
		  $obj.children(".window-content").children().children("object").css("width", width)
	               .css("height", height);
		}
        if(options.windowType=="iframe")		
	      $obj.children(".window-content").children("iframe").css("width", width)
	               .css("height", height);
		}
//移动
	var move = function($obj, x, y){
		x = parseInt(x);
		y = parseInt(y);
		$obj.attr("lastX",x)
		    .attr("lastY",y);
		x = x<=0?0:x;
		y = y<=0?0:y;
        x = x+"px";
		y = y+"px";		
		$obj.css("left", x)
	        .css("top", y)
	}
//拖拽
	var dragging = function(e, $obj){
	    if(options.draggable){
		e = e ? e : window.event;
		var t = parseInt($obj.css("top"));
		var l = parseInt($obj.css("left"));
		var r = parseInt($obj.css("right"));
		var b = parseInt($obj.css("bottom"));
		t = t<=0?0:t;
		l = l<=0?0:l;
		var x = e.clientX - lastMouseX;
		var y = e.clientY - lastMouseY;
		var o_w = options.width;
		var o_h = options.height;
		var win_height = $(window).height();
				var newx = l + x;
				var newy = t + y;
				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){
				if(options.onDragEnd != null)options.onDragEnd();
				$(document).unbind('mousemove');
				$(document).unbind('mouseup');
		    });
			if(options.onDragBegin != null)options.onDragBegin();
	    }
    });
	//绑定事件
	$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;
			$(document).bind('mousemove', function(e){
				resizing(e, $obj);
			});
			$(document).bind('mouseup', function(e){
				if(options.onResizeEnd != null)options.onResizeEnd();
				$(document).unbind('mousemove');
				$(document).unbind('mouseup');
			});
			if(options.onResizeBegin != null)options.onResizeBegin();
		}
    });
	//绑定事件
	$windowMinimizeButton.bind('click', function(e){
	    $obj = $(e.target).parent().parent();
		setFocus($obj);
		if($obj.attr("state") == "normal"){
	        $(e.target).parent().next().slideToggle("slow");
		}
    });
	//绑定事件
	$windowMaximizeButton.bind('click', function(e){
	  $obj = $(e.target).parent().parent();
	  setFocus($obj);
	  if($obj.attr("state") == "normal"){
		  if(options.windowType=="standard"){
		    $obj.animate({
		      top: "0px",
			  left: "0px",
			  width: $(window).width()-15,
			  height: $(window).height()-45
		    },"slow");
		  }else{
			tmpx = $obj.attr("lastX");
		    tmpy = $obj.attr("lastY");
			tmpwidth = $obj.attr("lastWidth");
		    tmpheight = $obj.attr("lastHeight");
			move($obj, 0, 0);
		    resize($obj,$(window).width()-15,$(window).height()-45);
			$obj.attr("lastX",tmpx);
		    $obj.attr("lastY",tmpy);
			$obj.attr("lastWidth",tmpwidth);
		    $obj.attr("lastHeight",tmpheight);
		  }
		  $obj.attr("state","maximized")
	  }else if($obj.attr("state") == "maximized"){
	    if(options.windowType=="standard"){ 
		  $obj.animate({
		    top: $obj.attr("lastY"),
			left: $obj.attr("lastX"),
			width: $obj.attr("lastWidth"),
			height: $obj.attr("lastHeight")
		  },"slow");
		}else{
		  resize($obj,$obj.attr("lastWidth"),$obj.attr("lastHeight"));
		  move($obj,$obj.attr("lastX"),$obj.attr("lastY"));
		}
		$obj.attr("state","normal")
	  }
    });
//关闭
	$windowCloseButton.bind('click', function(e){
		show_select();
	  $(e.target).parent().parent().fadeOut();
	  $(e.target).parent().parent().children(".window-content").html("");
	  if(options.closeAction !==''){
		  if(options.closeActionParam!=''){
			  options.closeAction(options.closeActionParam);	
			  }else{
				  options.closeAction();
				}
		  }
		if(options.showLayer){
			$.closeLayer();  
		}
		$("#"+roundStrings).remove();//采用随机隐藏层
		//$(".window-container").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.css("display","none");
	function _showWidow(){
		var $this = $(this);   
		$windowMinimizeButton.html(options.minimizeIcon);
		$windowMaximizeButton.html(options.maximizeIcon);
		$windowCloseButton.html(options.closeIcon);
		$windowResizeIcon.html(options.resizeIcon);
		$this.data("window",$windowContainer);
		var padding = parseInt(options.height/2);
	}
	return this.each(function(index) {
		var $this = $(this); 
		$windowMinimizeButton.html(options.minimizeIcon);
		$windowMaximizeButton.html(options.maximizeIcon);
		$windowCloseButton.html(options.closeIcon);
		$windowResizeIcon.html(options.resizeIcon);
		$this.data("window",$windowContainer);
		var c_h = options.height>options.width?options.width:options.height;
		var padding = parseInt((c_h/4)-20);
		
			$window = $this.data("window");
			$window.hide();
			$window.fadeIn("slow")
			$window.attr("id",roundStrings);
			if(options.ajaxURL != "" && options.windowType=='standard'){ 
				$.ajax({
				   beforeSend:function(){
					   if(options.loadingImg){
					 	var str = '<div style="margin:0pxa auto;"><img class="window_loading_img" style="padding-top:'+padding+'px;" src="'+options.loadingImg+'"/>';
 						$window.children(".window-content").html(str);
					   }
					},
				   type: "GET",
				   url: options.ajaxURL,
				   dataType: "html",
				   cache:false,
				   success: function(data){
					   if(options.appendContent!=''){
					 		$window.children(".window-content").html(data+appendContent);
					   }else{
						   $window.children(".window-content").html(data);
						}
					 if(options.onAjaxContentLoaded != null) options.onAjaxContentLoaded(); 
				   }
				 });
			}else if (options.content!=''){
				$window.children(".window-content").html(options.content);
			}else if(options.windowType=="iframe" && options.ajaxURL !=''){
var iframeData = '<iframe src="'+options.ajaxURL+'" frameborder="0" width=100%  height=100% scrolling="auto" id="ajax_content_ifram"></iframe>';
				$window.children(".window-content").html(iframeData)	
			}
			if(!options.draggable)
			    $window.children(".window-titleBar").css("cursor","default");
			setFocus($window);
            $window.fadeIn();
			if(options.showLayer){
				$.overLayer();
			}
		$('body').append($windowContainer);
	});
}})(jQuery);
