/**
 * @author Lukas Goldschmidt
 */

LG.wb.Class.Item = new Class({
//	An item representing a wikipage ...	

	initialize: function(brw,wpage) {
		this.wpage =wpage;
		this.images =new Object();
		this.alc = [];
		this.categories = [];
		this.links = [];
		this.Browser = brw;

		this.drift = new THREE.Vector3();
		this.dest = new THREE.Object3D();

		this.wpurl = this.Browser.wpurl; // 'http://en.wikipedia.org/w/api.php';
		this.alurl = this.Browser.alurl;
		var that = this;		

/*	Google Image search ... */
		var imageSearch = new google.search.ImageSearch();
		imageSearch.setSearchCompleteCallback(this, that.searchComplete, [imageSearch]);
		imageSearch.execute(wpage);

/*	Alchemy API */
	//	this.search_alchemy();

/*	Wikipedia Api Parse Page */
		this.search_wp();


/*	*/
		if(this.wpage.match(/\:/ig)){
			var col = "rgba(35, 165, 218, 1)";
		}else{
			var col = "rgba(218, 165, 32, 1)";
			
		}
		this.Label1 = this.makeLabel(300,60,this.wpage,col);
        	this.Label1.position.x =0;
        	this.Label1.position.y =220;
/*	*/

		this.deftbUrl = 'http://profile.ak.fbcdn.net/hprofile-ak-snc4/49868_1377623547_313_n.jpg';
		this.imgtex=THREE.ImageUtils.loadTexture(this.deftbUrl);
		this.imgmat= new THREE.MeshLambertMaterial({map: this.imgtex});
		this.sidemat=new THREE.MeshLambertMaterial( { color: 0x353535, shininess: 20, wireframe: false } );
		this.materials = [
			this.sidemat, // right
			this.sidemat, // left
			this.sidemat, //top
			this.sidemat, // bottom
			this.sidemat, // back
			this.imgmat, // front
		 ];
 	   
		var cubeGeometry = new THREE.CubeGeometry( 300, 300, 10 );
		this.model = new THREE.Mesh( cubeGeometry, this.materials );
		this.model.addChild(this.Label1);

/*	*/

		return this;
	},
	show: function(){this.model.visible=true;},
	hide: function(){this.model.visible=false;},
	makeLabel: function(w,h,t,col) {
	
		var geometry = new  THREE.PlaneGeometry( w, h, 3, 3);;
		var canvas = document.createElement( 'canvas' );
		canvas.width = w*2;
		canvas.height = h*2;
		var ctx = canvas.getContext("2d");
		ctx.fillStyle = "rgba(150, 150, 200, 0.4)";
		// Create gradients
		var lingrad = ctx.createLinearGradient(0,0,0,h*2);
		lingrad.addColorStop(0, '#666');
		lingrad.addColorStop(0.5, '#333');
		lingrad.addColorStop(0.5, '#333');
		lingrad.addColorStop(1, '#666');
		ctx.fillStyle = lingrad;
		ctx.globalAlpha = 0.6;
 		ctx.fillRect (0, 0, w*2, h*2);
  
		ctx.fillStyle = col;
		ctx.globalAlpha = 1;
		ctx.font         = 'bold 48px sans-serif';
		ctx.textBaseline = 'top';
		ctx.textAlign = 'center';

		if (ctx.fillText) {
			ctx.fillText(this.wpage, w, 2*h/3,w*2);
		}		
		var ret =  new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { map: new THREE.Texture(  canvas  )} ) );
		ret.doublesided=true;
		return ret;
	},
	search_wp: function(){
		// There are some site restrictions which make this workaround necessary ...
		var url = this.wpurl + "?action=parse&page=" + this.wpage + "&format=json&callback=LG.wb.App.Browser.items['" + str_clean(this.wpage) +  "'].wp_callback   " ;
		var elem = document.createElement ('script');
		elem.setAttribute ('src', url);
		elem.setAttribute ('type','text/javascript');
		document.getElementsByTagName ('head') [0].appendChild (elem);
	},
	search_alchemy: function(){
	// http://access.alchemyapi.com/ 
	// http://access.alchemyapi.com/calls/url/URLGetRankedNamedEntities?url=http://en.wikipedia.org/wiki/Al-Mansur&apikey=578452394758f01dd2b495e6106360faf61d2954&outputMode=json&jsonp=LG.wb.App.Browser.items['testpage'].alchemy_callback

		var url = this.alurl + "?url=" + this.wpurl.slice(0,this.wpurl.lastIndexOf("/")-1) + "wiki/" + this.wpage + "&apikey=578452394758f01dd2b495e6106360faf61d2954&outputMode=json&jsonp=LG.wb.App.Browser.items['" + str_clean(this.wpage) +  "'].al_callback   " ;
		var elem = document.createElement ('script');
		elem.setAttribute ('src', url);
		elem.setAttribute ('type','text/javascript');
		document.getElementsByTagName ('head') [0].appendChild (elem);
	
		
	},
	al_callback: function(data){
		var that = this;
		if(data['status']== 'OK'){
//			alert(data['language']);	
	  		$.each(data['entities'], function(key, val) {
	  			that.alc.push(val);
				if(val['disambiguated'] !== undefined && val['disambiguated'] !== this.wpage){
			//		that.Browser.display(val['disambiguated']['name']);	
					that.links.push(''+val['disambiguated']['name']);
				}

			});
		} else{
			console.log(data['status'] + ': ' + data['statusInfo']);	
		}
//  		$.each(data['parse']['categories'], function(key, val) {
//			$.each(val, function(key, val) {
		
	},
	wp_callback: function (data){
		// process received data
		var that = this;
  		$.each(data['parse']['categories'], function(key, val) {
			$.each(val, function(key, val) {
				if(key=="*"){
					if(val.search(/articles|wikipedia|all/i)<0){
		  	  			that.categories.push('Category:'+val);
					}
				}else{	/*	...  */		}
	  		});
  		});
		$.each(data['parse']['links'], function(key, val) {
			if(val['exists']=="" /* && !val['*'].match('/Wikipedia/gi') */ && val['ns'] == 0)
				  that.links.push(''+ val['*']);
		});
   	},
	searchComplete: function(searcher){
		// the Google Image search returned something
  		if (searcher.results && searcher.results.length > 0) {
  			this.images=searcher.results;
			this.setimage(this.images[Math.floor(Math.random()*this.images.length)].tbUrl);
		}
	},
	setimage:function(imgurl){
		// Set an Image out of our collection
		this.imgtex=THREE.ImageUtils.loadTexture(imgurl);
		this.imgmat= new THREE.MeshBasicMaterial({map: this.imgtex});
		this.materials = [
			this.sidemat, // right
			this.sidemat, // left
			this.sidemat, //top
			this.sidemat, // bottom
			this.sidemat, // back
			this.imgmat // front
		 ];
		this.model.materials=this.materials;		
	},
	goTo:function(x,y,z){
//		this.model.position.x = x;		
	//	this.model.position.y = z;		
//	this.model.position.z = y;		

		this.dest.position.x = x;		
		this.dest.position.y = z;		
		this.dest.position.z = y;		
	},
	animate: function(){
			this.model.lookAt(LG.wb.App.Browser.camera.position);
				
			this.drift.sub(this.dest.position,this.model.position); 
			if(! this.drift.isZero() ){
				this.model.position.addSelf(this.drift.multiplyScalar(0.5));
			}

			if(Math.random()<0.01)
				// occassionally change the image
				this.setimage(this.images[Math.floor(Math.random()*this.images.length)].tbUrl);
	},
} );
