// JavaScript Document
/*图片切换效果*/
$(function(){
     var len  = $("#title_num > p").length;
	 var index = 0;
	 var adTimer;
	 $("#icon_num li").mouseover(function(){
		index = $("#icon_num li").index(this);
		showImg(index);
	 }).eq(0).mouseover();	
	 $("#title_num p").mouseover(function(){
		index = $("#title_num p").index(this);
		showImg(index);
	 }).eq(0).mouseover();	
	 //滑入 停止动画，滑出开始动画.
	 $('#picBox').hover(function(){
			 clearInterval(adTimer);
		 },function(){
			 adTimer = setInterval(function(){
			    showImg(index)
				index++;
				if(index==len){index=0;}
			  } , 3000);
	 }).trigger("active");
})
// 通过控制left ，来显示不同的幻灯片
function showImg(index){
        var adWidth = $("#picBox").width();
		$("#show_pic").stop(true,false).animate({left : -adWidth*index},1000);
		$("#title_num p").removeClass("active")
			.eq(index).addClass("active");
		$("#text_num li").removeClass("active")
			.eq(index).addClass("active");
		$("#icon_num li").removeClass("active")
			.eq(index).addClass("active");
}

//图片滚动
$(function(){
    var page = 1;
    var i = 4; //每版放4个图片
	$("span.prev").animate({ opacity : "0"}, "fast");
	
    //向后 按钮
    $("span.next").click(function(){  
	     var $parent = $(this).parents("div.v_show");
		 var $v_show = $parent.find("div.v_content_list");
		 var $v_content = $parent.find("div.v_content"); 
		 var v_width = $v_content.width() ;
		 var len = $v_show.find("li").length;
		 var page_count = Math.ceil(len/i) ;
		 if( !$v_show.is(":animated") ){   
			if( page != page_count ){
				$("span.prev").animate({ opacity : "1"}, "fast");
				$v_show.animate({ opacity : "0.6"}, "fast");
				$v_show.animate({ left : '-='+v_width, opacity : "1" }, "slow");  //通过改变left值，达到每次换一个版面
				page++;
				if(page == page_count) {
					$(this).animate({ opacity : "0"}, "fast");
				}
			 }
		 }
		 $parent.find("span").eq((page-1)).addClass("current").siblings().removeClass("current");
   });
    //往前 按钮
    $("span.prev").click(function(){
	     var $parent = $(this).parents("div.v_show");
		 var $v_show = $parent.find("div.v_content_list"); 
		 var $v_content = $parent.find("div.v_content");
		 var v_width = $v_content.width();
		 var len = $v_show.find("li").length;
		 var page_count = Math.ceil(len/i) ;  
		 if( !$v_show.is(":animated") ){   
			if( page != 1 ){
				$("span.next").animate({ opacity : "1"}, "fast");
				$v_show.animate({ opacity : "0.6"}, "fast");
				$v_show.animate({ left : '+='+v_width, opacity : "1" }, "slow");
				page--;
				if(page == 1) {
					$(this).animate({ opacity : "0"}, "fast");
				}
			}
		}
		$parent.find("span").eq((page-1)).addClass("current").siblings().removeClass("current");
    });
});

/* 新闻右侧视频窗口选项卡 */
$(function(){
	    var $op =$("#videoTabMenu > ul > li > a");
	    $op.click(function(){
			var $par = $(this).parent(); //取得自己的父元素
            var index =  $op.parent().index($par); // 获取自己的父元素 在 全部li元素中的索引。
			$(this).addClass("current");           //当前<a>元素高亮
			$(this).parent().siblings().children("a").removeClass("current"); //去掉他父亲<li>元素的其它同辈<li>元素下<a>的高亮
						
			$("#videoTabBox > div")   	//选取子节点。不选取子节点的话，会引起错误。如果里面还有div 
					.eq(index).show()   //显示 <li>元素对应的<div>元素
					.siblings().hide(); //隐藏其它几个同辈的<div>元素
					
		})
	})

// 搜索框，鼠标点击，清除里面的值
$(function(){
	$('#searchinput').focus(function(){
			$(this).val('');
		})   
	})

//my add
$(function(){
	$(".ajaxbox").colorbox();
	$(".boxdel").colorbox({
		width:"50%", 
		inline:true, 
		href:"#confirmdiv",
		onOpen:function(){$("#confirm").attr("action",$(this).attr('href')); }
	});
})

function parseJSON(data){
	if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
	  return { status: 0, data: data.length ? data : 'Unspecified error' };
	}
	  return eval('(' + data + ');');
}

/*
 * @autocomplete 
 */
$.fn.autocomplete = function(options){
	var defaults={
		url: 'index.php?s=/ajax/autocomplete',
		chars: 1,
		width: 300,
		height: 150,
		top: null,
		left: null,
		time: 400,
		sroll: false
	};
	var ops = $.extend(defaults,options);
	var pop = $('<div id="autocomplete"></div>');
	var results = $('<ul id="results"></ul>');
	var doneUsers = {};
	var curPos;
	if(ops.top != null){pop.css('top',ops.top);}
	if(ops.left != null){pop.css('left',ops.left)}
	$(this).after(pop).parent().css('position','relative');
	pop.css({'width':ops.width+'px'}).hide().append(results);
	if(ops.sroll){
		pop.css({'height':ops.height+'px','overflow':'auto'});
	}
	function quest(q,elem){
		var w = $.trim(q.substr(q.lastIndexOf(',')+1,q.length));
		if(w.length >= ops.chars){
			curPos = null;
			$.ajax({
				type: 'GET',
				url: ops.url+'/prefix/'+w,
				cache: false,
				success: function(data){
					jdata = parseJSON(data);
					if(jdata.length > 0){
						loadDone(elem);
						var str = '';
						if(jdata.length > 10){
							results.css({overflow:'auto',height:'240px'});
						}else{
							results.css({overflow:'hidden',height:'auto'});
						}
						for(var j = 0; j < jdata.length;j++){
							if(! doneUsers[jdata[j]]){
								str += '<li>'+jdata[j]+'</li>';
							}
						}
						results.html(str);
						updataePos(results.children('li').eq(0))
						results.children('li').mouseover(function(){
							updataePos($(this));
						}).click(function(){
							addValue($(this).text(),elem);
						})
						if(results.children('li').size() > 0){
							pop.show();
						}else{
							pop.hide();
						}
					}else{
						pop.hide();
					}
				}
			});	
		}
	}
	$(document).click(function(){
		pop.hide();
	});
	pop.click(function(){stopBubble();});
	function loadDone(elem){
		doneUsers = {};
		var dones = elem.val().split(',');
		for(var i = 0; i < dones.length; i++){
			doneUsers[$.trim(dones[i])] = true;
		}
	}
	function updataePos(elem){
		curPos = elem;
		results.children('li').removeClass('popPos');
		curPos.addClass('popPos');
	}
	function addValue(v,elem){
		var defaultValue = elem.val();
		var tmp = '';
		if(defaultValue.indexOf(',') >= 0){
			tmp = defaultValue.substr(0,defaultValue.lastIndexOf(',')+1)+v;
		}else{
			tmp = v;
		}
		elem.val(tmp);
		results.html('');
		pop.hide();
	}
	return $(this).each(function(){
		$(this).attr('autocomplete','off');
		var outKey = [9,13,38,40];
		$(this).bind('keyup',function(e){
			var newVal = $(this).val();
			switch (e.keyCode) {
			    case 16: // shift
			    case 17: // ctrl
			    case 18: // alt
			    case 20: // caps lock
			    case 33: // page up
			    case 34: // page down
			    case 35: // end
			    case 36: // home
			    case 37: // left arrow
			    case 38: // up arrow
			    case 39: // right arrow
			    case 40: // down arrow
			      		return true;
			
			    case 9:  // tab
			    case 13: // enter
			    case 27: // esc
			     		 return true;
			    default: //all other keys
				    if(newVal.length >= ops.chars){
						quest(newVal,$(this));	
					}else{
						pop.hide();
					}
			}	
		}).bind('keydown',function(e){
			if(e.keyCode == 9 || e.keyCode == 13){
				if(curPos){
					loadDone($(this));
					var tv = curPos.text();
					if(!doneUsers[tv]){
						addValue(tv,$(this));	
					}
				}
				stopDefault(e);
				return false;
			}else if(e.keyCode == 38){
				if(curPos.prev().length > 0){
					return updataePos(curPos.prev());	
				}
				return false;
			}else if(e.keyCode == 40){
				if(curPos.next().length > 0){
					return updataePos(curPos.next());
				}
				return false;
			}
		});
	});
};


function stopBubble(e){
	if(e && e.stopPropagation){
		e.stopPropagation();	
	}else{
		window.event.cancelBubble = true;	
	}	
}

jQuery.fn.LoadImage=function(scaling,width,height,loadpic){
    if(loadpic==null) loadpic="loading.gif";
	return this.each(function(){
		var t=$(this);
		var src=$(this).attr("src")
		var img=new Image();
		//alert("Loading...")
		img.src=src;
		//自动缩放图片
		var autoScaling=function(){
			if(scaling){
			
				if(img.width>0 && img.height>0){ 
			        if(img.width/img.height>=width/height){ 
			            if(img.width>width){ 
			                t.width(width); 
			                t.height((img.height*width)/img.width); 
			            }else{ 
			                t.width(img.width); 
			                t.height(img.height); 
			            } 
			        } 
			        else{ 
			            if(img.height>height){ 
			                t.height(height); 
			                t.width((img.width*height)/img.height); 
			            }else{ 
			                t.width(img.width); 
			                t.height(img.height); 
			            } 
			        } 
			    } 
			}	
		}
		//处理ff下会自动读取缓存图片
		if(img.complete){
		    //alert("getToCache!");
			autoScaling();
		    return;
		}
		$(this).attr("src","");
		var loading=$("<img alt=\"Loading...\" title=\"Loading...\" src=\""+loadpic+"\" />");
		
		t.hide();
		t.after(loading);
		$(img).load(function(){
			autoScaling();
			loading.remove();
			t.attr("src",this.src);
			t.show();
			//alert("finally!")
		});
		
	});
}

jQuery.fn.DrawImage=function(width,height,loadpic){
    if(loadpic==null) loadpic="loading.gif";
	return this.each(function(){
		var t=$(this);
		/*
		if(t.parent('div')) {alert(1);
			width=t.parent('div').width();
			height=t.parent('div').height();
		}else{*/
			width=t.parent().parent().width();
			height=t.parent().parent().height();
		//}
		//alert(width);
		var src=$(this).attr("src")
		var img=new Image();
		//alert("Loading...")
		img.src=src;
		//自动缩放图片
		var autoScaling=function(){
				if(img.width>0 && img.height>0){
			        if(img.width/img.height>=width/height){
			            if(img.width>width){//alert(1);
			                t.width((img.width*height)/img.height); 
			                t.height(height);
			                //var margin=(boxWidth-$("#img1").width())/2;
											//t.css("margin-left",-20);
			            }else{//alert(2);
			                //t.width(img.width); 
			                //t.height((height*img.width)/width);
			                t.width((img.width*height)/img.height); 
			                t.height(height);
			            }
			            var margin=-(t.width()-width)/2;
									t.css("margin-left",margin);
			        } 
			        else{
			            if(img.height>height){//alert(3);
			            	t.height((img.height*width)/img.width); 
			              t.width(width);
			            }else{//alert(4);
			            	t.width(width); 
			              t.height((img.height*width)/img.width); 
			                
			            }
			            var margin=-(t.height()-height)/2;
									t.css("margin-top",margin);
			        } 
			    } 
		}
		//处理ff下会自动读取缓存图片
		if(img.complete){
		    //alert("getToCache!");
			autoScaling();
		    return;
		}
		$(this).attr("src","");
		var loading=$("<img alt=\"Loading...\" title=\"Loading...\" src=\""+loadpic+"\" />");
		
		t.hide();
		t.after(loading);
		$(img).load(function(){
			autoScaling();
			loading.remove();
			t.attr("src",this.src);
			t.show();
			//alert("finally!")
		});
		
	});
}

function showDirText(id){
    	//$("#dirtext_"+id).show();
    	$("#dirtext_"+id).slideDown();
    	for(i=0;i<10;i++){
    		if($("#dirtext_"+i).length!=0 && i!=id) $("#dirtext_"+i).slideUp();
    	}
}
function getMapDirection(id,lat,lng,toaddr){
    	var addr = $("#addr_"+id).val();
    	var city = $("#city_"+id).val();
    	if(addr=="" || addr=="Street Address" || city=="" || city=="City,State or ZIP"){
    		alert("Please input Address and City!");
    	}else{
    		var map;
    		var directionsPanel;
    		var directions;
   	 		map = new GMap2(document.getElementById("map_"+id));
      	map.setCenter(new GLatLng(lat,lng), 15);
      	directionsPanel = document.getElementById("route_"+id);
      	directions = new GDirections(map, directionsPanel);
      	//directions.load("from: "+addr+", "+city+" to: "+toaddr, {travelMode:G_TRAVEL_MODE_WALKING});
      	directions.load("from: "+addr+", "+city+" to: "+toaddr, {travelMode:G_TRAVEL_MODE_DRIVING});
    	}
}

/** 
fromid:源list的id. 
toid:目标list的id. 
moveOrAppend参数("move"或者是"append"): 
move -- 源list中选中的option会删除.源list中选中的option移动到目标list中,若目标list中已存在则该option不添加. 
append -- 源list中选中的option不会删除.源list中选中的option添加到目标list的后面,若目标list中已存在则该option不添加. 

isAll参数(true或者false):是否全部移动或添加 
*/ 
function select2select(fromid,toid,moveOrAppend,isAll) {
    if(moveOrAppend.toLowerCase() == "move") { //移动 
        if(isAll == true) { //全部移动 
            $("#"+fromid+" option").each(function() { 
                //将源list中的option添加到目标list,当目标list中已有该option时不做任何操作. 
                $(this).appendTo($("#"+toid+":not(:has(option[value="+$(this).val()+"]))")); 
            }); 
            $("#"+fromid).empty(); //清空源list 
        } 
        else if(isAll == false) { 
            $("#"+fromid+" option:selected").each(function() { 
                //将源list中的option添加到目标list,当目标list中已有该option时不做任何操作. 
                $(this).appendTo($("#"+toid+":not(:has(option[value="+$(this).val()+"]))")); 
                //目标list中已经存在的option并没有移动,仍旧在源list中,将其清空. 
                if($("#"+fromid+" option[value="+$(this).val()+"]").length > 0) { 
                    $("#"+fromid).get(0) 
                    .removeChild($("#"+fromid+" option[value="+$(this).val()+"]").get(0)); 
                } 
            }); 
        } 
    } 
    else if(moveOrAppend.toLowerCase() == "append") { 
        if(isAll == true) { 
            $("#"+fromid+" option").each(function() { 
                $("<option></option>") 
                .val($(this).val()) 
                .text($(this).text()) 
                .appendTo($("#"+toid+":not(:has(option[value="+$(this).val()+"]))")); 
            }); 
        } 
        else if(isAll == false) { 
            $("#"+fromid+" option:selected").each(function() { 
                $("<option></option>") 
                .val($(this).val()) 
                .text($(this).text()) 
                .appendTo($("#"+toid+":not(:has(option[value="+$(this).val()+"]))")); 
            }); 
        } 
    } 
}; 

function selectAllOption(selectid){
	 $("#"+selectid+" option").each(function() {
       $(this).attr("selected",true); 
  	}); 
}

