var URL_API_BATTLE = './api/battle/battle.php';
var URL_API_COMMENT = './api/comment/ranking.php';
var URL_DETAIL_HEAD = 'index.php?module=Snap&action=Detail&sid=';
var TIME_LATEN_THUMBNAIL = 500;
var LEFT=0;
var RIGHT=1;
var VOTE_WINNER_INNERHTML = '<strong>●</strong>';
var COMMENT_DEFAULT = " 付近で撮影しました";


//Event.observe(window, 'load', function(){ init(); }, false);
function init(){
	
	battle.init({
		idContainer : 'btlContainer',
		idHistHead : 'btlHist',
		idHistTmpl : 'btlTpl',
		idThmbContainer : 'btlThmbContainer',
		idThmbHead : 'btlThmbHist',
		idThmbTmpl : 'btlThmbTpl',
		classHist : 'btlClass',
		classThmbHist : 'btlThmbClass',
		sex : 0
	});
	comment.init({
		inputid: 'rFCtext',
		formid: 'rFC',
		tmplid: 'btlCmntTpl',
		cmntclass: 'rinfocomments',
		cmntCntnrid: 'ric',
		url : URL_API_COMMENT,
		ev : 1
	});
}

function onCSnap(lr,idWin,idLose,ev){
	battle.evaluate(lr,idWin,idLose,ev);
}

function onMOvSnap(id){
	$('comment_poplist_'+id).style.display='block';
}

function onMOtSnap(id){
	$('comment_poplist_'+id).style.display='none';
}

var battle = {};
battle = {
	iPreload : 0,
	iNow : 0,
	idContainer : '',
	idHistHead : '',
	idHistTmpl : '',
	idThmbContainer : '',
	idThmbHead : '',
	idThmbTmpl : '',
	classHist : '',
	classThmbHist : '',
	sex : 0,				// boy:1 girl:2 all:0
	opt : {
		time : 0,
		unit : 0
	},
	defaultOptions : {
		time : 0.5*1000,	// [ms]
		unit : 25			// [ms]
	},
	evaluate : function(lr,idWin,idLose,ev){
		this.requestPreload( this.sex, idWin, idLose, ev );
		Effect.Fade($(this.idHistHead+this.iNow), {
			duration : 0.3
		});
		var classes = document.getElementsByClassName('voteRslt',$(this.idThmbHead+this.iNow));
		classes[lr].addClassName('voteSelect');
		classes[lr].innerHTML = VOTE_WINNER_INNERHTML;
		classes[1-lr].addClassName('voteNoSelect');
		if(battle.iNow>=11){
			$(this.idThmbContainer).removeChild($(this.idThmbHead+(this.iNow-10)));
		}
		Effect.BlindRight( $(this.idThmbHead+this.iNow),{
			duration:0.3
			,delay:0.8 } );
		this.iNow++;
		Effect.Appear($(this.idHistHead+this.iNow), {
			duration : 0.3
			,delay:0.4
			,afterFinish : function(){ Element.setOpacity($(battle.idHistHead+battle.iNow),0.9999); }
		});
	},
	update : function(){
	},
	init : function( o ){
		this.iPreload = 0;
		this.iNow = 0;
		this.idContainer = o.idContainer;
		this.idHistHead = o.idHistHead;
		this.idHistTmpl = o.idHistTmpl;
		this.classHist = o.classHist;
		this.idThmbContainer = o.idThmbContainer;
		this.idThmbHead = o.idThmbHead;
		this.idThmbTmpl = o.idThmbTmpl;
		this.classThmbHist = o.classThmbHist;
		this.sex = o.sex;
		this.opt.time = this.defaultOptions.time;
		this.opt.unit = this.defaultOptions.unit;
		if( o ){
			this.opt.time = ( o.time ) ? o.time : this.defaultOptions.time;
			this.opt.unit = ( o.unit ) ? o.unit : this.defaultOptions.unit;
		}
		$(this.idContainer).innerHTML = '';
		this.requestPreload( this.sex, 0, 0, 1 );
		$(this.idHistHead+'0').style.display = 'block';
		this.requestPreload( this.sex, 0, 0, 1 );
	},
	res : function( o ){
		var result = eval( '(' + o.responseText + ')' );
		var snap, comment;
		for( var j=0; j<=1; j++ ){
			snap = result.snaps[j];
			snap.shotplace = (snap.shotplace) ? snap.shotplace : "";
			comment = (snap.modelcomment) ? ((snap.modelcomment.length>27) ? (snap.modelcomment.substring(0,24)+'...') : snap.modelcomment) : snap.shotplace.substring(0,18)+COMMENT_DEFAULT;
			result.snaps[j].modelcomment = comment;
		}
		var rendered = Lyase.View.render({element:battle.idHistTmpl}, result );
		$(battle.idHistHead+result.i).innerHTML = rendered;

		// thumbnail
		var rendered2 = Lyase.View.render({element:battle.idThmbTmpl}, result );
		$(battle.idThmbHead+result.i).innerHTML = rendered2;
	},
	//cb : function( json ){
	//	var rendered = Lyase.View.render({element:battle.idHistTmpl}, json );
	//	$(battle.idHistHead+json.i).innerHTML = rendered;
		// thumbnail
	//	var rendered2 = Lyase.View.render({element:battle.idThmbTmpl}, json );
	//	$(battle.idThmbHead+json.i).innerHTML = rendered2;
	//},
	requestPreload : function( sex, idWin, idLose, ev ){
		var divPreload = document.createElement('div');
		divPreload.setAttribute('id',this.idHistHead+this.iPreload);
		divPreload.className = this.classHist;
		divPreload.style.display = 'none';
		$(this.idContainer).appendChild(divPreload);

		// thumbnail
		var divThumbnail = document.createElement('div');
		divThumbnail.setAttribute('id',this.idThmbHead+this.iPreload);
		divThumbnail.className = this.classThmbHist;
		divThumbnail.style.display = 'none';
		$(this.idThmbContainer).insertBefore(divThumbnail,$(this.idThmbContainer).firstChild);

		//var pars = 'i='+this.iPreload+'&s='+sex+'&w='+idWin+'&l='+idLose+'&e='+ev+'&cb=battle.cb';
		//var jsonpr = new JSONscriptRequest( URL_API_BATTLE+'?'+pars );
		var pars = 'i='+this.iPreload+'&s='+sex+'&w='+idWin+'&l='+idLose+'&e='+ev;
		var aj = new Ajax.Request( URL_API_BATTLE, {method: 'get', parameters: pars, onComplete: battle.res} );

		this.iPreload++;
		if( this.iPreload>3 ){
			$(this.idContainer).removeChild($(this.idContainer).childNodes[0]);
		}
	},
	cancel : function(){
		$(this.opt.center).style.zIndex = 0;
		$(this.opt.center).style.width = this.opt.width+'px';
		this.reset();
		clearInterval( this.timer );
		this.timer = 0;
	}
};


function isNew(s){
	// dispdate example:"2006-11-02 16:09:39"
	var ddate = s.dispdate;
	if( !ddate ){
		return 0;
	}
	var arrDate = ddate.split(' ')[0].split('-');
	var date = new Date(parseInt(arrDate[0]),parseInt(arrDate[1])-1,parseInt(arrDate[2]));
	var now = new Date();
	var diff = now.getTime()-date.getTime();
	return (diff<1000*60*60*24*14) ? 1 : 0;
}



// jsr_class.js
//
// JSONscriptRequest -- a simple class for making HTTP requests
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//
//
// Sample Usage:
//
// <script type="text/javascript" src="jsr_class.js"></script>
// 
// function callbackfunc(jsonData) {
//      alert('Latitude = ' + jsonData.ResultSet.Result[0].Latitude + 
//            '  Longitude = ' + jsonData.ResultSet.Result[0].Longitude);
//      aObj.removeScriptTag();
// }
//
// request = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&
//            output=json&callback=callbackfunc&location=78704';
// aObj = new JSONscriptRequest(request);
// aObj.buildScriptTag();
// aObj.addScriptTag();
//
//


// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;

    // modified by M.Ohtsuka make it all in one
    this.buildScriptTag();
    this.addScriptTag();
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

// new effect by M.Ohtsuka
Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, 
    Object.extend({ scaleContent: false, 
      scaleY: false,
      scaleFrom: 0,
      scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
      restoreAfterFinish: true,
      afterSetup: function(effect) {
        effect.element.makeClipping();
        effect.element.setStyle({height: '0px'});
        effect.element.show(); 
      },
      afterFinishInternal: function(effect) {
        effect.element.undoClipping();
      }
    }, arguments[1] || {})
  );
}