function left(str, count){
	var length = str.length;
	if(count > (length -1)){
		count =(length -1);
	}
	return str.substring(0, count);
}

function isEqualDate(createdDate, publishDate){
	var createdDateTime=createdDate.time;
	var publishDateTime=publishDate.time;
	return ((publishDateTime - createdDateTime) / 60000) < 10;
}

function delayDay(publishDate){
	var time=publishDate.time;
	var now = new Date();
	var nowTime=now.getTime();
	return (nowTime - time) / (1000 * 60 * 60 * 24);
}

function addFav1() {
    if (document.all) {
        window.external.addFavorite(location.href, document.title);
    }
    else if (window.sidebar) {
        window.sidebar.addPanel(document.title, location.href, "");
    }
}
function setHomepage() {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage(location.href);
    }
    else if (window.sidebar) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert(e);
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', location.href);
    }
}

function change(index) {
    if (typeof (isround) != 'undefined') clearTimeout(isround);

    var imgs = $("#imgs li");
    var tips = $("#tips li");

    for (var i = 0; i < tips.length; i++) {
        $("#imgs li:eq(" + i + ")").hide();
        $("#tips li:eq(" + i + ")").removeClass("curr");
    }
    $("#imgs li:eq(" + index + ")").fadeIn('slow', function() {});
    $("#tips li:eq(" + index + ")").addClass("curr");

    if ((next = index + 1) == $("#tips li").length) next = 0;
    isround = setTimeout('change(' + next + ')', 2000);
}

function changeGamePage(index, sortType, threshold) {
    var pLeft = -710 * index;
    if ($("#gamelist .main").position().left != pLeft) {
        $(".game .title").find("li").removeClass("curr");
        $(".game .title").find("li:eq(" + index + ")").addClass("curr");
        $("#gamelist .main").animate({ opacity: "1", left: -710 * index + "px" }, 1000);
    }
		var url="/asych/lsresource";
		$.getJSON(url, {
				sort: sortType,
				threshold: threshold,
				resourceTypeId: "1"
		}, function(data) {
				var str=genResourceHTml(data, "1", sortType);
				$("#gamelist_main ul:eq("+index+")")[0].innerHTML=str;
		});
}
function changeSoftPage(index, sortType, threshold) {
    var pLeft = -710 * index;
    if ($("#softlist .main").position().left != pLeft) {
        $(".soft .title").find("li").removeClass("curr");
        $(".soft .title").find("li:eq(" + index + ")").addClass("curr");

        $("#softlist .main").animate({ opacity: "1", left: -710 * index + "px" }, 1000);
    }
		var url="/asych/lsresource";
    $.getJSON(url, {
				sort: sortType,
				threshold: threshold,
				resourceTypeId: "2"
		}, function(data) {
				var str=genResourceHTml(data, "2", sortType);
				$("#softwarelist_main ul:eq("+index+")")[0].innerHTML=str;
		});
}

//更改后下载模块方法--替换
function changeDownPage(index) {
    var pLeft = -409 * index;
    if ($("div.downlistbottom").position().left != pLeft) {
        $("ul.downaddr li").removeClass("curr");
        $("ul.downaddr li:eq(" + index + ")").addClass("curr");
        $("div.downlistbottom").animate({ opacity: "1", left: pLeft + "px" }, 1000);
    }
}

function rMouseover(target) {
	$(target).addClass("curr");
	$(target).find("span").show();
}

function rMouseOut(target){
	$(target).removeClass("curr");
	$(target).find("span").hide();
}

function readySoftwareChange(){
	$(".soft .main").find("li").mouseover(function() {
		$(this).addClass("curr");
		$(this).find("span").show();
	});
	$(".soft .main").find("li").mouseout(function() {
		$(this).removeClass("curr");
		$(this).find("span").hide();
	});
}

function readyGameChange(){
	$(".game .main").find("li").mouseover(function() {
		$(this).addClass("curr");
		$(this).find("span").show();
	});
	$(".game .main").find("li").mouseout(function() {
		$(this).removeClass("curr");
		$(this).find("span").hide();
	});
}
function readyNetgameChange(){
  $(".netgame .main").find("li").mouseover(function() {
    $(this).addClass("curr");
    $(this).find("span").show();
  });
  $(".netgame .main").find("li").mouseout(function() {
    $(this).removeClass("curr");
    $(this).find("span").hide();
  });
}
function readyClentTagChange(){
  $(".clientTag .list").find("li").mouseover(function() {
      $(this).addClass("curr");
  }).mouseout(function() {
      $(this).removeClass("curr");
  });
}

function readyComment(){
	$("#comment").keydown(function(e) {
		if (!e) var e = window.event;
		if (e.ctrlKey && e.keyCode == 13) {
				$("#submit").click();
		}
	});
}

function readyLigthBox(){
	$("#screenlist li:gt(0)").hide();
  $("#screenlist li a").lightBox();
}

function readyIsp(){
    if(getCookie("isp")==null){
        $.getJSON("http://211.147.5.155:7021/iplib/getIsp?format=json&jsoncallback=?",
                function(json){
                    showDown(json.isp);
                    setCookie("isp",json.isp);
                }
        );
    }else{
        showDown(getCookie("isp"));
    }
}

function showDown(isp){
    if(isp == "电信"){
      $(".loadlist").each(function(){
        dianxin = $(this).find(".dianxin");
        wangtong = $(this).find(".wangtong");
        $(this).find(".wangtong").replaceWith(dianxin);
        $(this).find(".dianxin").after(wangtong);
      });
    }
}

function changeEqpGamePage(index, sortType, threshold, resourceTypeId, resolutionId, osId) {
		var pLeft = -741 * index;
		if ($("#gamelist .game").position().left != pLeft) {
				$("#contenter .main .title").find("li").removeClass("curr");
				$("#contenter .main .title").find("li:eq(" + index + ")").addClass("curr");
				$("#gamelist .game").animate({ opacity: "1", left: pLeft + "px" }, 1000);
		}
		var url="/asych/lsresource";
		$.getJSON(url, {
				sort: sortType,
				threshold: threshold,
				resourceTypeId: resourceTypeId,
				osId:osId,
				resolutionId:resolutionId
		}, function(data) {
				var str=genResourceHTml(data, resourceTypeId, sortType);
				$("#gamelist_main ul:eq("+index+")")[0].innerHTML=str;
		});
}

function changeNetgamePage(index, sortType, threshold) {
	var pLeft = -710 * index;
	if ($("#netgamelist .main").position().left != pLeft) {
		$(".netgame .title").find("li").removeClass("curr");
		$(".netgame .title").find("li:eq(" + index + ")").addClass("curr");
		$("#netgamelist .main").animate({ opacity: "1", left: -710 * index + "px" }, 1000);
	}
	var url="/asych/lsnetgame";
	$.getJSON(url, {
			sort: sortType,
			threshold: threshold
	}, function(data) {
			var str=genNetgameHTml(data, sortType);
			$("#netgamelist_main ul:eq("+index+")")[0].innerHTML=str;
	});
}

function moreWithOS(){
  var resourceTypeId=$("#hResourceType").attr("value");
  var resolutionId=$("#resolutionId").attr("value")
  var osId=$("#osId").attr("value");
  var resource="game";
  switch(resourceTypeId){
    case '1':resource="game";break;
    case '2':resource="software";break;
  }
  window.open("/"+resource+"/update-1/?r="+resolutionId+"&o="+osId);
}

var UPDATE_DESC_ID = "1";

function genResourceHTml(data, resourceTypeId, sortType){
	var list=data.model.resources;
	var str="";
	var urlType="game";
	if(resourceTypeId == "1"){
		urlType="game";
	}else if(resourceTypeId == "2"){
		urlType="software";
	}
	for(var i = 0; i<list.length; i++){
		var resource=list[i];
		str=str + "<li onmouseover=\"rMouseover(this);\" onmouseout=\"rMouseOut(this);\">";
		var isEqual=isEqualDate(resource.createdDate, resource.publishDate);
		var delay=delayDay(resource.publishDate)
		if(isEqual && delay < 2 && UPDATE_DESC_ID != sortType){
			str=str + "<strong>最新上线</strong>";
		}else if(!isEqual && delay < 2 && UPDATE_DESC_ID != sortType){
			str=str + "<strong>最新更新</strong>";
		}
		str=str + "<a href=\"/" + urlType + "/" + resource.id + ".html\" title=\"" + resource.name + "\">";
		str=str + "<img src=\"" + resource.icon + "\" alt=\"" + resource.name + "\"/></a>";
		str=str + "<a href=\"/" + urlType + "/" + resource.id + ".html\" title=\"" + resource.name + "\">";
		str=str + resource.name;
		str=str + "</a><p>" + left(resource.description, 40) + "</p>";
		str=str + "<span class=\"star" + resource.stars + "\"></span></li>"
	}
	return str;
}

function genNetgameHTml(data, sortType){
	var list=data.model.resources;
	var str="";
	var urlType="netgame";
	for(var i = 0; i<list.length; i++){
		var resource=list[i];
		str=str + "<li onmouseover=\"rMouseover(this);\" onmouseout=\"rMouseOut(this);\">";
		if(sortType === "recommend"){
		}else{
    		var isEqual=isEqualDate(resource.createdDate, resource.publishDate);
    		var delay=delayDay(resource.publishDate)
    		if(isEqual && delay < 2 && UPDATE_DESC_ID != sortType){
    			str=str + "<strong>最新上线</strong>";
    		}else if(!isEqual && delay < 2 && UPDATE_DESC_ID != sortType){
    			str=str + "<strong>最新更新</strong>";
    		}
		}
		str=str + "<a href=\"/" + urlType + "/" + resource.id + ".html\" title=\"" + resource.name + "\">";
		str=str + "<img src=\"" + resource.icon + "\" alt=\"" + resource.name + "\"/></a>";
		str=str + "<a href=\"/" + urlType + "/" + resource.id + ".html\" title=\"" + resource.name + "\">";
		str=str + resource.name;
		str=str + "</a><p>" + left(resource.description, 40) + "</p>";
		str=str + "<span class=\"star" + resource.stars + "\"></span></li>";
	}
	return str;
}

function goClick(index, osId, resolutionId){
		var resourceTypeId=document.getElementById("hResourceType").value;
		changeEqpGamePage(index, "hot", 10, resourceTypeId, resolutionId, osId);
		document.getElementById("index").value=index;
		document.getElementById("osId").value=osId;
}

function goChange(resolutionId){
	 var resourceTypeId=document.getElementById("resourceTypeId").value;
	 var index=document.getElementById("index").value;
	 var osId=document.getElementById("osId").value;
	 changeEqpGamePage(index, "hot", 10, resourceTypeId, resolutionId, osId);
	 document.getElementById("hResourceType").value=resourceTypeId;
}

function readyEqpGameChange(){
	$(".main .game").find("li").mouseover(function() {
		$(this).addClass("curr");
		$(this).find("span").show();
	});
	$(".main .game").find("li").mouseout(function() {
		$(this).removeClass("curr");
		$(this).find("span").hide();
	});
}

function readyEqpLigthBox(){
  $("#snapshot_list li a").lightBox();
}

function changeEqpSnapshotPage(pos, totalCnt){
	pageCnt=parseInt(totalCnt/5);
	var index=document.getElementById("snapshot_index").value;
	if(totalCnt%5 != 0){
	  pageCnt=pageCnt+1;
	}
	index=index-pos;
	if(index < 0){
	   index = 0;
	}
  var pLeft = -715 * index;
	if ($("#snapshot_list").position().left != pLeft && pageCnt > index) {
			$("#snapshot_list").animate({ opacity: "1", left: pLeft + "px" }, 1000);
			document.getElementById("snapshot_index").value=index;
	}
}

$.fn.infiniteCarousel = function () {
  function repeat(str, num) {
      return new Array( num + 1 ).join( str );
  }

  return this.each(function () {
      var $wrapper = $('> div', this).css('overflow', 'hidden'),
          $slider = $wrapper.find('> ul'),
          $items = $slider.find('> li'),
          $single = $items.filter(':first'),
          
          singleWidth = $single.outerWidth(), 
          visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
          currentPage = 1,
          pages = Math.ceil($items.length / visible);

      // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
      if (($items.length % visible) != 0) {
          //$slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
          $slider.append($items.slice(0, visible - ($items.length % visible)).clone().addClass('cloned'));
          $items = $slider.find('> li');
      }

      // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
      $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
      $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
      $items = $slider.find('> li'); // reselect
      
      // 3. Set the left position to the first 'real' item
      $wrapper.scrollLeft(singleWidth * visible);
      
      // 4. paging function
      function gotoPage(page) {
          var dir = page < currentPage ? -1 : 1,
              n = Math.abs(currentPage - page),
              left = singleWidth * dir * visible * n;
          
          $wrapper.filter(':not(:animated)').animate({
              scrollLeft : '+=' + left
          }, 500, function () {
              if (page == 0) {
                  $wrapper.scrollLeft(singleWidth * visible * pages);
                  page = pages;
              } else if (page > pages) {
                  $wrapper.scrollLeft(singleWidth * visible);
                  // reset back to start position
                  page = 1;
              } 

              currentPage = page;
          });
          
          return false;
      }
      
      $wrapper.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
      
      // 5. Bind to the forward and back buttons
      $('a.back', this).click(function () {
          return gotoPage(currentPage - 1);
      });
      
      $('a.forward', this).click(function () {
          return gotoPage(currentPage + 1);
      });
      
      // create a public interface to move to a specific page
      $(this).bind('goto', function (event, page) {
          gotoPage(page);
      });
      
      // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
      $(this).bind('next', function () {
          gotoPage(currentPage + 1);
      });
  });
}
