var sliderRef;


function HvRect(rx,ry,rw,rh){
	this.x = rx;
	this.y = ry;
	this.w = rw;
	this.h = rh;
}

function makeSlider(containerId,rect,btnLeft,btnRight){
	sliderRef = new slider(containerId,rect,btnLeft,btnRight);
}

function slider(containerId,rect,btnLeft,btnRight){

	this.static = [];
	this.twacc = [];
	
	// scrname:アカウント名 , boxclass:CSSクラス（twitter Hivelo,twitterアカウント名,labo,blog...そのクラスによって背景画像が変わるはず）, twc:読み込むtweets数
	this.twacc[0] = { scrname:"hivelocityinc", boxclass:"mainNavi01_box" , boxpict:null , twc:16 };
	this.twacc[1] = { scrname:"fukumitsu76", boxclass:null , boxpict:"mainNavi05_bg.jpg" , twc:16 };
	this.boxDisplayed = 4; // 一つのページのボックスカウント
	this.maxBoxes = 16;
	this.boxW = 192; // ボックスの幅
	this.boxH = 190; // ボックスの高さ
	this.boxMarginLR = 39; // 基本的に、左と右のボタンの幅
	this.buttonsH = 84;
	this.pageWH = 6; // 下のページボックスの幅／高さ
	this.pageActiveColor = '#0080FF'; // 選ばれたページの色
	this.pageInactiveColor = '#D0D0D0'; // 見えないページの色
	this.sliderContainerMargin = 2;
	this.horizontalTopIndent = -20;
	
	// DO NOT EDIT FROM HERE
	
	this.twaccloaded = 0;
	this.staticsLoaded = 0;
	this.isBuildingBoxes = false;
	this.rebuildBoxes = false;
	this.boxTop = 0;
	this.boxLeft = 0;
	this.pagesBoxes = [];
	this.boxes = [];
	this.tweets = [];
	this.firstTweet = null;
	this.rect = rect;
	this.orientation = ( this.rect.w > this.rect.h ? "h" : "v" );
	if( this.orientation == "v" ){
		this.maxBoxes = 4;
	}
	this.container = document.getElementById(containerId);
	this.sliderContainer = document.createElement('div');
	this.sliderContainer.style.position = 'absolute';
	this.sliderContainer.style.display = 'block';
	this.sliderContainer.style.width = this.rect.w + 'px';
	this.sliderContainer.style.height = this.rect.h + 'px';
	this.sliderContainer.style.left = this.sliderContainerMargin + 'px';
	this.sliderContainer.style.top = '0px';
	this.sliderContainer.style.overflow = 'hidden';
	//addAttributeToElement(this.sliderContainer, 'style', "position:absolute;display:block;width:"+this.rect.w+"px;height:"+this.rect.h+"px;left:"+this.sliderContainerMargin+"px;top:0px;overflow:hidden;");
	this.container.appendChild(this.sliderContainer);
	
	this.btnLeft  = ( btnLeft == null ? null : document.getElementById(btnLeft) );
	this.btnRight = ( btnRight == null ? null : document.getElementById(btnRight) );
	
	this.boxMargin = 0;
	this.index = 0;
	this.isSliding = false;
	
	if( this.btnLeft != null ){
		this.btnLeft.onclick = function(){ sliderRef.animLeft(); };
		this.btnLeft.style.position = 'absolute';
		this.btnLeft.style.left = '2px';
		this.btnLeft.style.top = (this.rect.h/2) - (this.buttonsH) + this.horizontalTopIndent + 'px';
	}
	
	if( this.btnRight != null ){
		this.btnRight.onclick = function(){ sliderRef.animRight(); };
		this.btnRight.style.position = 'absolute';	
		this.btnRight.style.left = (this.rect.w - this.boxMarginLR - 2)+'px';
		this.btnRight.style.top = (this.rect.h/2) - (this.buttonsH) + this.horizontalTopIndent + 'px';
	}
	
	

	// Load static promotion

	var staticScriptElt = document.createElement('script');
  	staticScriptElt.type = 'text/javascript';
 	staticScriptElt.src = "/wp-content/themes/hivelocity/staticPromo.js.php";
 	document.getElementsByTagName('head')[0].appendChild(staticScriptElt);
	

	// Load tweets
	
	var i;
	for( i = 0; i < this.twacc.length; i++ ){
		if( this.orientation == "v" ){
			this.twacc[i].twc = 4;
		}
		var scriptElt = document.createElement('script');
  		scriptElt.type = 'text/javascript';
 		scriptElt.src = "http://twitter.com/statuses/user_timeline/"+this.twacc[i].scrname+".json?callback=twitterCallback&count="+this.twacc[i].twc;
 		document.getElementsByTagName('head')[0].appendChild(scriptElt);
	}
	
}

slider.prototype.receiveStatics = function(statics){
	this.staticsLoaded = 1;
	this.static = statics;
	this.placeBoxes();
};

slider.prototype.receiveTweets = function(twitters){
	//alert("test");
	if( twitters.constructor.toString().indexOf("Array") >= 0 ){
		var i = 0;
		var j = 0;
		  
		var statusHTML = [];
		for (var i=0; i<twitters.length; i++){ 
		  var boxclass = "";
		  var boxpict = "";
		  for(j=0;j<this.twacc.length;j++){
			if(this.twacc[j].scrname == twitters[i].user.screen_name){
				boxclass = this.twacc[j].boxclass;
				boxpict = this.twacc[j].boxpict;
				break;
			}
		  }
		  if( (i == 0) && (twitters[i].user.screen_name == "hivelocityinc") ){
			  this.firstTweet = { tw:twitters[i] , bc:boxclass , bp:boxpict , twdelta:relative_delta(twitters[i].created_at) };
		  }
		  else{
			  this.tweets.push({ tw:twitters[i] , bc:boxclass , bp:boxpict , twdelta:relative_delta(twitters[i].created_at) }); 
		  }
		  
		}
	}
	
	this.twaccloaded += 1;
	
	if( (this.twaccloaded == this.twacc.length) && (this.staticsLoaded == 1) ){
	  this.tweets.sort(function(a,b){
		return (a.twdelta > b.twdelta ? 1 : -1);
	  });
	  this.placeBoxes();
	}
};

slider.prototype.placeBoxes = function(){
	//alert("placeBoxes");
	if( this.isBuildingBoxes ){
		this.rebuildBoxes = true;
		return;
	}
	
	this.isBuildingBoxes = true;
	
	// Reset
	
	this.boxes = [];
	this.pagesBoxes = [];
	this.sliderContainer.innerHTML = "";
	if ( this.sliderContainer.hasChildNodes() ){
	    while ( this.sliderContainer.childNodes.length >= 1 ){
	        this.sliderContainer.removeChild( this.sliderContainer.firstChild );       
	    } 
	}
	
	
	// Build
	
	var i = 0;
	
	if( this.orientation == "h" ){
		this.boxTop = (this.rect.y + (this.rect.h/2) - (this.boxH/2)) + this.horizontalTopIndent;
		this.boxMargin = ((this.rect.w - (this.boxMarginLR*2) - (this.boxW * this.boxDisplayed))/(this.boxDisplayed+1));
		this.boxLeft = this.rect.x + this.boxMarginLR + this.boxMargin;
	}
	else{
		this.boxLeft = (this.rect.x + (this.rect.w/2) - (this.boxW/2));
		this.boxMargin = ((this.rect.h - (this.boxMarginLR*2) - (this.boxH * this.boxDisplayed))/(this.boxDisplayed+1));
		this.boxTop = 19;//this.rect.y + this.boxMarginLR + this.boxMargin;
	}
	
	var boxLink;
	var box;
	var boxesCount = 0;
	var boxCssId = "box";

	if( this.firstTweet != null ){
				
		this.addTweetBox(this.firstTweet.tw, (boxCssId + this.boxes.length), this.firstTweet.bc, this.firstTweet.bp , this.boxTop , this.boxLeft);
		
	}
	
	var staticsCount = ( this.firstTweet == null ? this.static.length : 3 );
	
	for(i=0; (i < this.static.length) && (i < staticsCount); i++){
		 
		this.addStaticBox(this.static[i].url, this.static[i].alt, (boxCssId + this.boxes.length), this.boxTop, this.boxLeft, this.static[i].pict);
		
	}

	for(i=0; (i < this.tweets.length) && (this.boxes.length<this.maxBoxes); i++){
		
		this.addTweetBox(this.tweets[i].tw, (boxCssId + this.boxes.length), this.tweets[i].bc, this.tweets[i].bp , this.boxTop , this.boxLeft );
		
	}
	
	
	if( this.orientation == "h" ){
		var pagesCount = Math.ceil(this.boxes.length/this.boxDisplayed);
		
		var pT = this.rect.h - (this.pageWH * 2) + this.horizontalTopIndent;
		var pFL = this.rect.x + ( (this.rect.w/2) - (((pagesCount*(this.pageWH*2))-this.pageWH)/2) );
		
		for(i=0;i<pagesCount;i++){
			var pageBox = document.createElement('div');
			var pL = pFL + (i * (this.pageWH*2));
			var pC = ( i == 0 ? this.pageActiveColor : this.pageInactiveColor );
			pageBox.style.position = 'absolute';
			pageBox.style.display = 'block';
			pageBox.style.width = this.pageWH + 'px';
			pageBox.style.height = this.pageWH + 'px';
			pageBox.style.top = pT + 'px';
			pageBox.style.left = pL + 'px';
			pageBox.style.backgroundColor = pC;
			
			this.pagesBoxes.push(pageBox);
			this.sliderContainer.appendChild(pageBox);
		}
	}
	
	this.isBuildingBoxes = false;
	
	if( this.rebuildBoxes ){
		this.rebuildBoxes = false;
		this.placeBoxes();
	}
	
	this.index = 0;
	
};

slider.prototype.updatePages = function(){
	var i;
	for( i = 0; i < this.pagesBoxes.length; i++ ){
		this.pagesBoxes[i].style.backgroundColor = ( (i*this.boxDisplayed) == this.index ? this.pageActiveColor : this.pageInactiveColor );
	}
};

slider.prototype.animLeft = function(){
	if( !this.isSliding && (this.index > 0) ){
		this.isSliding = true;
		this.index -= this.boxDisplayed;
		var i = 0;
		for( i = 0; i < this.boxes.length; i++ ){
			$("#box"+i).animate({"left":"+="+(this.rect.w-this.boxMargin)},"slow",function(){ sliderRef.handleAnimationComplete(); });
		}
		this.updatePages();
	}
};

slider.prototype.animRight = function(){
	if( !this.isSliding && (this.index < (this.boxes.length - this.boxDisplayed)) ){
		this.isSliding = true;
		this.index += this.boxDisplayed;
		var i = 0;
		for( i = 0; i < this.boxes.length; i++ ){
			$("#box"+i).animate({"left":"-="+(this.rect.w-this.boxMargin)},"slow",function(){ sliderRef.handleAnimationComplete(); });
		}
		this.updatePages();
	}
};

slider.prototype.handleAnimationComplete = function(){
	this.isSliding = false;
};

slider.prototype.addTweetBox = function( tweet , id , boxClass , boxImage , top , left ){
	
	var box = document.createElement('dl');
	box.id = id;
	box.style.position = "absolute";
	box.style.top = top + 'px';
	box.style.left = left + 'px';
	box.style.width = this.boxW + 'px';
	box.style.height = this.boxH + 'px';
	box.style.margin = '0px';
	box.style.padding = '0px';
	box.style.color = '#000000';
	box.style.textAlign = 'left';
	box.style.backgroundColor = '#FFFFFF';
	if(boxImage != null){
		box.style.backgroundImage = 'url(/wp-content/themes/hivelocity/shared/img/' + boxImage + ')';
	}
	if(boxClass != null){
		var bClss = document.createAttribute('class');
		bClss.nodeValue = boxClass;
		box.setAttributeNode(bClss);
	}
	//box.style.zIndex = '0';
	
	box.innerHTML = '<div style="position:absolute;width:148px;height:53px;top:65px;left:22px;font-size:13px;overflow:hidden">' + tweet.text.substring(0,50) + '</div><div style="position:absolute;width:90px;height:25px;top:132px;left:27px;font-size:13px;">'+ relative_time(tweet.created_at) +'</div>' ;
	
	
	this.boxes.push(box);
	
	var boxLink = document.createElement('a');
	boxLink.style.textDecoration = 'none';
	
	var boxLinkHref = document.createAttribute('href');
	boxLinkHref.nodeValue = 'http://twitter.com/'+tweet.user.screen_name+'/status/'+tweet.id_str
	boxLink.setAttributeNode(boxLinkHref);
	
	var boxLinkTarget = document.createAttribute('target');
	boxLinkTarget.nodeValue = '_blank';
	boxLink.setAttributeNode(boxLinkTarget);
	
	boxLink.appendChild(box);
	this.sliderContainer.appendChild(boxLink);

	this.increaseBoxesCount();
	

};

slider.prototype.addStaticBox = function( linkUrl , linkAlt , id , top , left , picture ){
	
	var box = document.createElement('div');
	box.id = id;
	box.style.position = "absolute";
	box.style.top = top + 'px';
	box.style.left = left + 'px';
	box.style.width = this.boxW + 'px';
	box.style.height = this.boxH + 'px';
	box.style.margin = '0px';
	box.style.padding = '0px';
	box.style.color = '#000000';
	box.style.textAlign = 'left';
	box.style.backgroundColor = '#FFFFFF';
	box.style.backgroundImage = 'url(/wp-content/themes/hivelocity/shared/img/' + picture + ')';
	//box.style.zIndex = '0';
	this.boxes.push(box);
	
	var boxLink = document.createElement('a');
	
	var boxLinkHref = document.createAttribute('href');
	boxLinkHref.nodeValue = linkUrl;
	boxLink.setAttributeNode(boxLinkHref);
	
	var boxLinkTarget = document.createAttribute('target');
	boxLinkTarget.nodeValue = '_blank';
	boxLink.setAttributeNode(boxLinkTarget);
	
	boxLink.appendChild(box);
	this.sliderContainer.appendChild(boxLink);

	this.increaseBoxesCount();
	
};

slider.prototype.increaseBoxesCount = function(){
	
	if( this.orientation == "h" ){
		this.boxLeft += this.boxW + this.boxMargin;
		if( (this.boxes.length % this.boxDisplayed) == 0 ){
			this.boxLeft += this.boxMarginLR * 2;
		}
	}
	else{
		this.boxTop += this.boxH + this.boxMargin;
		if( (this.boxes.length % this.boxDisplayed) == 0 ){
			this.boxTop += this.boxMarginLR * 2;
		}
	}
	
};

function relative_delta(time_value){
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);
	return delta;
}

function relative_time(time_value) {
  var delta = relative_delta(time_value);
  if (delta < 60) {
    return delta+'秒前';
  } else if(delta < 120) {
    return '1分間前';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + '分間前';
  } else if(delta < (120*60)) {
    return '1時間前';
  } else if(delta < (24*60*60)) {
    return '' + (parseInt(delta / 3600)).toString() + ' 時間前';
  } else if(delta < (48*60*60)) {
    return '1日前';
  } else {
    return (parseInt(delta / 86400)).toString() + ' 日前';
  }
}

function twitterCallback(twitters) {
  //alert("twitterCallback");
  sliderRef.receiveTweets(twitters);
}

function staticPromoCallback(statics){
  //alert("staticPromoCallback");
  sliderRef.receiveStatics(statics);
}

function addAttributeToElement( element , attributeName , attributeValue ){
	//var attribute = document.createAttribute(attributeName);
	//attribute.nodeValue = attributeValue;
	element.setAttribute(attributeName,attributeValue);
}

function loadTweets(){
	makeSlider("slider_container",new HvRect(0,0,900,300),"btnLeft","btnRight");
}




