var $tag = $(".topad"), ads = [{url:"http://count.haoting.com/geci_ad_counter.asp?url="+escape("cp.boheshop.com/mc/index.asp?ccid=21027"), name:"睡觉减肥--瘦到你尖叫！"},
							   {url:"http://count.haoting.com/geci_ad_counter.asp?url="+escape("lt.boheshop.com/index.asp?ccid=20052"), name:"美女喝汤丰胸-绝了"},
							   {url:"http://count.haoting.com/geci_ad_counter.asp?url="+escape("xjn.pinwei100.cn/index.asp?ccid=826020"), name:"祛斑-美白--李湘出绝招"},
							   {url:"http://count.haoting.com/geci_ad_counter.asp?url="+escape("xw.huchao123.com/index.asp?id=000015"), name:"韩国女性去痘去疤有绝招"}],
sort = function(array){
	array.sort(function(a,b){  
		return Math.random()-0.5 > 0 ? 1 :-1;
	});
	
	return array;
}, insert =  function(i){
	$("<div><a target='_blank'></a></div>").appendTo($tag).find('a').attr("href",ads[i%4].url).html(ads[i%4].name);
}, init = function(){
	sort(ads);
	
	$tag.empty();
	
	for(var i=0;i<ads.length;i++){
		insert(i);
	}
	
	insert(4);
}, swap = function(index){
	var $divs = $tag.children("div"), $this = $divs.eq(index), copy = [0,1,2,3], copy2 = [], prev = index -1;
	
	if(prev <0)	prev=3;
	
	for(var i = 0 ;i <copy.length; i++){
		if( i === prev) continue;
		copy2.push(copy[i]);
	}

	var obj = sort(copy2)[0];
	if(obj === index)	return;
	var $obj=$divs.eq(obj), $objclone = $obj.clone(true), $clone = $this.clone(true);
	$this.replaceWith($objclone);
	$obj.replaceWith($clone);
	
	if(index === 0){
		var $div4 = $divs.eq(4);
		$div4.replaceWith($objclone.clone(true).removeClass().addClass("4"));
	}

	if(obj===0){
		var $div4 = $divs.eq(4);
		$div4.replaceWith($clone.clone(true).removeClass().addClass("4"));
	}
};

init();

var counter = -1, index = 0;
var time = setInterval(function(){
								
	if(counter < 7){
		if(counter%2==0){//$tag.text((new Date()).getSeconds());
			$tag.animate({scrollTop : "+=25px"},1000);
			if(counter == 6){
				swap(index = 0);
			}else{
				swap(++index);
			}
		}
	}else if(counter == 7){
		$tag.scrollTop(0);
	}else if(counter == 8){
		$tag.animate({scrollTop : "+=25px"},1000);
		swap(++index);
	}
	var _count = counter;
	counter = (counter+1) %10;
	
	if(_count > 0 && counter === 0){
		counter=2;
	}
},2500);

var resize = function(){
	$("#outer").width($("#geci .content").width());
};

resize();
$(window).resize(resize);