/*
 * ajaxPopup - jQuery Plugin
 * http://www.uuoke.com
 *
 * Copyright (c) 2010 yihunet
 *
 * $Date: 2011/02/14 02:02:35 $
 * $version: 1.0.1
 */
jQuery(function($) {
	var userAgent = navigator.userAgent.toLowerCase();
	var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
	var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
	var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
	var is_safari = (userAgent.indexOf('webkit') != -1 || userAgent.indexOf('safari') != -1);
    var divArray = new Array();
    var activeID;
	$.fn.ajaxPopup =  function(options){
		if (!this)
			return false;

		var defaults = {     
				center:true,
				timeout:0,
				drag:true,
				modal:false,
				json:false 
 
			  };	    
	    var opts = $.extend(defaults, options);     

		return this.each( 
				 function() {
 
			var me = $(this);
			
			if(opts.content!=null){
				me 
				.unbind('click.ajaxPopup')
				.bind('click.ajaxPopup', function(e) {return  popupByContent(e,this,opts)});

			}else if (this.nodeName.toLowerCase() == 'form') {
				
				if (this.enctype == 'multipart/form-data') {

				    me
				    .unbind('submit.ajaxPopup')
				    .bind('submit.ajaxPopup', function(e) {return popupByIframeForm(e,this,opts)});
					
				}else{
				
				    me
				    .unbind('submit.ajaxPopup')
				    .bind('submit.ajaxPopup', function(e) {return popupByAjaxForm(e,this,opts)});
				}
			
				 
			}else if(this.nodeName.toLowerCase() == 'a'){
				me 
				.unbind('click.ajaxPopup')
				.bind('click.ajaxPopup', function(e) {return  popupByLink(e,this,opts)});
				 
			}
		}); 

	};
	
	$.ajaxPopup = {
		  hidden : function(id){return hiddenPopup(id)},
		  remove : function(id){return removePopup(id)},
		  show:function(id){return showPopup(id)},
		  getActive:function(){
                                if(activeID==null) return null;
                                return document.getElementById(activeID);
		                      },
		  open:function (options,e){
		                    	var defaults = {     
		                  				center:true,
		                  				timeout:0,
		                  				drag:true,
		                  				modal:false,
		                  				json:false
		                  			  };	
		                  	    var opts = $.extend(defaults, options);
		                  	
		                    	var content = opts.content;
		                  		var title = opts.title!=null? opts.title:'';
		                  		var src = null;
		                  		if(e) 
		                  			src = e.srcElement || e.target; // 获取触发事件的源对象
		                  		else 
		                  			opts.center = true;
		                  		 

		                  		var divobj = initDiv(e,src,opts);
		                  		divobj.style.display = '';
		                  		setDivContent(divobj,title,content);
		                  		setDivPosition(e,divobj,opts); 
		                  		if (opts!=null && typeof opts.success == 'function'){
		                  			opts.success(content);
		                  	    }
		                  		$('.popup').ajaxPopup();
		                     }
		 
	};
	
	var popupByContent = function(e,me,opts){
		e.preventDefault();
		var content = opts.content;
		var title = opts.title!=null? opts.title:'';
		var divobj = initDiv(e,null,opts);
			divobj.style.display = '';
			setDivContent(divobj,title,content);
		    //setDivPosition(e,divobj,opts); 
		    if (typeof opts.success == 'function'){
				 opts.success(content);
	        }
	};
	
	var popupByLink = function(e,me,options){
		e.preventDefault();   
		var url = me.href;
	
		var p =  url.indexOf('?') != -1  ? '&':'?';
		url+=p+'popup=1&_dc='+Math.random();
		
		if(options.json){
			url+= url.indexOf('json=') !=-1 ? '':'&json=1'
		}
	
		var divobj = initDiv(e,me,options);
		divobj.style.display = '';
	    var  title = me.title !='' ? me.title:'';
	    title = options.title!=null ? options.title:title;
		$.ajax({
			 type: "get",
			 url: url,
			 dataType:options.json ? 'json':'html',
			 success:function(res){
			 
			 var content_html = "";
			 if(options.json){
				 for(var msg in res.messages){
					 if(res.messages[msg].message)
					   content_html+=(res.messages[msg].message)+"<br>";
				 }
				 title =  title =='' ? res.title:'';
			 }else{
				 
				 content_html = filterScripts(res);
			 }
			 
			 
			 title =  title =='' ?  '':title;
			 setDivContent(divobj,title,content_html);
			 setDivPosition(e,divobj,options);
			 
			     
			 if ( typeof options.success == 'function'){
			    	  options.success(res);
			  }
			 
              $('.popup').ajaxPopup();
			  },
			  error:function(){
				      $('#'+divobj.id+'_inner').html(url+"请求错误！");
				      setTimeout(function (){$.ajaxPopup.remove(divobj.id)}, 3000);
				  
			      }
		 });
		 //doane(e);
		return false;
	}; 
	
	var setDivContent = function(divobj,title,content){
		
		activeID = divobj.id;
		
        $('#'+divobj.id+'_title').html(title);
		
		$('#'+divobj.id+'_inner').html(content);
		
		
		
	};
	
	var popupByIframeForm = function(e,me,options){

		e.preventDefault();   
	    var hidden_iframe_id = 'popup_hidden_iframe_'+me.id;
	    var hidden_iframe = document.getElementById(hidden_iframe_id);
	    if(hidden_iframe==null){
	    	if (is_ie && !is_opera) {
	    		hidden_iframe = document.createElement("<iframe name='" + hidden_iframe_id + "' id='" + hidden_iframe_id + "'></iframe>");
			} else {
				hidden_iframe = document.createElement("iframe");
				hidden_iframe.name = hidden_iframe_id;
				hidden_iframe.id = hidden_iframe_id;
			}
	    	hidden_iframe.style.display = 'none';
	    
	    	 $('body').prepend(hidden_iframe);
	    	
	    }
	   
	    me.target = hidden_iframe_id;
	    
	    //$(me).prepend('<input type="hidden" name="popup" value="1" />');
	  
	    //if(options.json) 
	    	 //$(me).prepend('<input type="hidden" name="json" value="1" />');
 
	    var url = me.action;
		
		var p =  url.indexOf('?') != -1  ? '&':'?';
		
		url+=p+'popup=1&_dc='+Math.random();
		
		if(options.json){
			url+= url.indexOf('json=') !=-1 ? '':'&json=1'
		}

		var title = options.title!=null ? options.title:'';
		

	    $(hidden_iframe).bind("load",function (e){
	    	 setTimeout(function (){postIframeLoad(e,me,options)},20);
	    
	    });
	    
	    me.action = url;
   	    me.submit();
   	    setTimeout(function (){
   	     
   	      divobj = initDiv(e,me,options); divobj.style.display = '';
 		
   	    }, 1);
   	    
	}; 
	
	var postIframeLoad = function(e,me,options){
		var data;
		try{
			data = $('#popup_hidden_iframe_'+me.id).contents().find("body").html();
			
			//alert(data)
    
		}catch(e){
			  $('#'+divobj.id+'_inner').html(me.action+"请求错误！");
		      setTimeout(function (){$.ajaxPopup.remove(divobj.id)}, 3000);
		}
		
		if(data!=null){
			  var content_html = filterScripts(data);
			  
			  var  title = me.title !='' ? me.title:'';
			      title = options.title!=null?options.title:title;

			      setDivContent(divobj,title,content_html);
			   
			      //setDivPosition(e,options);  
		}
	};
	
	var fieldValue = function(el, successful) {
		var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
		if (typeof successful == 'undefined') successful = true;

		if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
			(t == 'checkbox' || t == 'radio') && !el.checked ||
			(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
			tag == 'select' && el.selectedIndex == -1))
				return null;

		if (tag == 'select') {
			var index = el.selectedIndex;
			if (index < 0) return null;
			var a = [], ops = el.options;
			var one = (t == 'select-one');
			var max = (one ? index+1 : ops.length);
			for(var i=(one ? index : 0); i < max; i++) {
				var op = ops[i];
				if (op.selected) {
					var v = op.value;
					if (!v) // extra pain for IE...
						v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
					if (one) return v;
					a.push(v);
				}
			}
			return a;
		}
		return el.value;
	};
	
	var formToArray = function(form,semantic) {
		var a = [];

		var els = semantic ? form.getElementsByTagName('*') : form.elements;

		if (!els) return a;
		
		for(var i=0, max=els.length; i < max; i++) {
			var el = els[i];
			var n = el.name;
			if (!n) continue;

			if (semantic && form.clk && el.type == "image") {
				// handle image inputs on the fly when semantic == true
				if(!el.disabled && form.clk == el) {
					a.push({name: n, value: $(el).val()});
					a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
				}
				continue;
			}

			var v = fieldValue(el, true);
			if (v && v.constructor == Array) {
				for(var j=0, jmax=v.length; j < jmax; j++)
					a.push({name: n, value: v[j]});
			}
			else if (v !== null && typeof v != 'undefined')
				a.push({name: n, value: v});
		}

		if (!semantic && form.clk) {
			// input type=='image' are not found in elements array! handle it here
			var $input = $(form.clk), input = $input[0], n = input.name;
			if (n && !input.disabled && input.type == 'image') {
				a.push({name: n, value: $input.val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
		}
		return a;
	};
	
	var popupByAjaxForm = function(e,me,options){
        e.preventDefault();   
        if (typeof options.onsubmit == 'function'){
			if(!options.onsubmit()){
                    return false;
			}
	    }
	
    	//var data = $(me).serializeArray();
		var data = formToArray(me,true);
		data.push({name: 'popup', value: 1});
	    if(options.json) data.push({name: 'json', value: 1});
		var url = me.action;
		var p =  url.indexOf('?') != -1  ? '&':'?';
		url+=p+'&_dc='+Math.random();
		//var dataType = 'html';
		//if(options.json) dataType='json';
		
		//var  title = me.title !='' ? me.title:'';
		var  title = me.title !='' ? me.title:'';
	    title = options.title!=null ? options.title:title;
		var divobj = initDiv(e,me,options);
		divobj.style.display = '';

		$.ajax({
			url: url,
			data: data,
			dataType:options.json ? 'json':'html',
			type: $(me).attr('method') ? $(me).attr('method') : 'get',
			success: function(res){
				 var content_html = "";

				 if(options.json){
					 for(var msg in res.messages){
						 if(res.messages[msg].message)
						   content_html+=(res.messages[msg].message)+'<br>';
					 }
					 title =  title =='' ? res.title:'';
				 }else{
					 
					 content_html = filterScripts(res);
				 }
				 
				 title =  title =='' ?  '':title;
				 setDivContent(divobj,title,content_html);
				 //setDivPosition(e,divobj,options);  
				 
                 if (typeof options.success == 'function'){
						if(options.success){
			                    options.success(res);
						}
				 }
                 //重新绑定默认的事件
				 //alert('重新绑定默认的事件');
                 $('.popup').ajaxPopup();
				    
		    },
			error: function(){
			      $('#'+divobj.id+'_inner').html(url+"请求错误！");
			      setTimeout(function (){$.ajaxPopup.remove(divobj.id)}, 3000);
		      }
		});
	};
	
	var initDiv = function (e,sourceobj,options){
		 //var ctrlid = sourceobj.id==''   ? divCount : sourceobj.id ;
		var sourceid = sourceobj!=null? $(sourceobj).attr('id'):'';
		var divobj = document.getElementById(sourceid + '_ajaxPopup');
		
		//alert('activeid:'+activeID);
		 //如果当前有活动窗口则在当前活动窗口中显示
		 if(activeID!=null &&  !options.modal ){
			 
			 divobj = document.getElementById(activeID);
		 }
		 
		 
 
		 if(options.center ) {
			 divclass = 'popupmenu_centerbox';
		 } else {
			 divclass = 'popupmenu_popup';
		 }
		 
		//new div
         var isNewdiv = false;
		 if(!divobj) {
			divobj = document.createElement('div');
			isNewdiv = true;
 
			 
			divobj.id = sourceid + '_ajaxPopup';
			
			
			
			//divobj.style.display = 'none';
			divobj.className = divclass;
			divobj.style.position = 'absolute';
			
			if(options.modal){
				
				$("body").prepend('<div id="ajaxPopupMask_wrapper" style="display: block; z-index: 100; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;"></div>');
				
				$("#ajaxPopupMask_wrapper").append('<div id="ajaxPopupMask_bg" style="background-color: rgb(2, 2, 2); position: absolute; overflow: hidden; top: 0px; left: 0px; height: 100%; width: 100%; opacity: 0.75;filter:alpha(opacity=30);"></div>');
				
				$("#ajaxPopupMask_wrapper").append(divobj);
		 
				$("#ajaxPopupMask_wrapper").css({height:document.body.scrollHeight}); 
				
				divArray.push(divobj.id);
				
				 
			}else{
				
				$("body").prepend(divobj);
				divArray.push(divobj.id);
				
		        divobj.style.zIndex = 50+divArray.length;
 
				
			}
		}
		
		
		
		if(divobj.style.clip && !is_opera) {
			divobj.style.clip = 'rect(auto, auto, auto, auto)';
		}
		
	    var  maxh = 1000;
		if(maxh && divobj.scrollHeight > maxh) {
			divobj.style.height = maxh + 'px';
			if(is_opera) {
				divobj.style.overflow = 'auto';
			} else {
				divobj.style.overflowY = 'auto';
			}
		}
		
        
    	//if(is_ie) {
			//divobj.style.filter += "progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";
		//}
		
	
		
    	if(!is_opera) {
    		divobj.style.clip = 'rect(auto, auto, auto, auto)';
		}
    	
    	
	
		var popupmenu_inner = '<div class="loader">Loading...</div>';
 		

		
		 var s = '<h1 id="'+divobj.id+'_title">消息</h1><a id="'+divobj.id+'_close" href="javascript:void(0);" class="float_del" title="关闭">关闭</a><div id="'+divobj.id+'_inner" class="popupmenu_inner">' + popupmenu_inner + '<div>';
	 
		
		 divobj.innerHTML = s;
		
		//绑定关闭按钮事件 
		$('#'+divobj.id+'_close').click( function (){
			removePopup(divobj.id);
			if (options!=null && typeof options.closehandle == 'function'){
				options.closehandle(content);
      	    }
			 
		});
		
		//绑定活动窗口事件
		 
		$(divobj).bind("mouseover",function(event){ 
			  if(isMouseLeaveOrEnter(event,this)){activeID = divobj.id;$('#debug').val(activeID);}
		});
		
		//$(divobj).bind("mouseout",function(event){
			  //if(isMouseLeaveOrEnter(event,this)){activeID = null;$('#debug').val(activeID);}
		//});
		
		if(options.drag) {
			setdrag(divobj);
		}
 
	    if(isNewdiv || !options.center)
		 setDivPosition(e,divobj,options);
		 
		return divobj;

	};

	function isMouseLeaveOrEnter(e, handler) {
	    if (e.type != 'mouseout' && e.type != 'mouseover') return false;
	    var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	    while (reltg && reltg != handler)
	        reltg = reltg.parentNode;
	    return (reltg != handler);
	}
	
	
	function setDivPosition(e,divobj,options) {
		if(divobj) {

			var sTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
			var cTop = document.documentElement && document.documentElement.clientHeight?document.documentElement.clientHeight : document.body.clientHeight;
			var cLeft = document.documentElement && document.documentElement.clientWidth?document.documentElement.clientWidth : document.body.clientWidth;
			
			divobj.w = divobj.offsetWidth;
			divobj.h = divobj.offsetHeight;
			if(!options.center) {
				  
				if(e){
					
					 divobj.style.top= e.clientY+sTop+10+ 'px';
					
					if(e.clientX>(cLeft/2)){
						   divobj.style.left= e.clientX + document.body.scrollLeft-20 - divobj.w+'px';
					}else{ 
					   divobj.style.left=e.clientX+document.body.scrollLeft+10+ 'px';;	
					}
				}
			
			} else  {//center
			 
				if(cTop>700) cTop = 700;
				 divobj.style.left = (cLeft-divobj.w)/2 + 'px';
				 divobj.style.top = (cTop-divobj.h)/2 + sTop+'px';
			}
			
		}
	}
	
	function hiddenPopup(id) {
		if(id!=null){
		   var div = document.getElementById(id); 
		   div.style.display = 'none';
		}else{
			$('.popupmenu_centerbox').hide();
			$('.popupmenu_popup').hide();
		}
		$('#ajaxPopupMask_bg').remove();
		$('#ajaxPopupMask_wrapper').remove();
	}
	
	function removePopup(id){
		try{
		if(id!=null){
			   var div = document.getElementById(id); 
			   if(div) $(div).remove(); 
			}else{
				$('.popupmenu_centerbox').remove(); 
				$('.popupmenu_popup').remove();
			}
		$('#ajaxPopupMask_bg').remove();
		$('#ajaxPopupMask_wrapper').remove();}
		catch(e){}
	}
	
    function showPopup(id){
    	if(id!=null){
 		   var div = document.getElementById(id); 
 		   div.style.display = '';
 		}else{
 			$('.popupmenu_centerbox').show();
 			$('.popupmenu_popup').show();
 		}
    }
    function doane(event) {
		e = event ? event : window.event;
		if(is_ie) {
			e.returnValue = false;
			e.cancelBubble = true;
		} else if(e) {
			e.stopPropagation();
			e.preventDefault();
		}
	}
	
	function filterScripts(data) {
		// Removing the body, head and html tag
		if (typeof data == 'string')
		 return	data = data.replace(/<\/?(html|head|body|!DOCTYPE)([^>]*)>/gi, '');
		   
	}
	
	

	function in_array(needle, haystack) {
		if(typeof needle == 'string' || typeof needle == 'number') {
			for(var i in haystack) {
				if(haystack[i] == needle) {
						return true;
				}
			}
		}
		return false;
	}

	function setdrag(obj){
	   var draging = false;
	   var startLeft,startTop;
	   var startX,startY;
				 
	    //$(obj).css('cursor','move');
	   
	   var objtitle = document.getElementById(obj.id);
	  
		$(objtitle).mousedown(function(event){
	     var offset = $(obj).offset();
					startLeft = offset.left;
					startTop = offset.top;
					startX = event.clientX;
					startY = event.clientY;
					draging = true;
				}).mousemove(function(event){
					if (draging == false)return;
					var deltaX = event.clientX - startX;
					var deltaY = event.clientY - startY;
					var left = startLeft + deltaX;
					var top = startTop + deltaY;
					$(obj).css('left',left+'px').css('top',top+'px');
				}).mouseup(function(event){
					draging = false;
				});
	}

	function keyHandler(event) {
		
		event = window.event || event;

		var keyCode = event.keyCode || event.which || event.charCode;


		if (keyCode == 27) {
			 removePopup(activeID);
		} 
	}
    
	$(document).bind('keydown.ajaxPopup', keyHandler);
    
    $('.popup').ajaxPopup();
    $('.popupcf').ajaxPopup({center:false});
});
