/* 
	Widget Module
	2009-01-08
*/
var MSG_CLEARALL = "All photos will be deleted. Do you still want to proceed?";
var MSG_CANVAS_MIN = "Canvas cannot be shortened anymore.";
var MSG_CANVAS_MAX = "Canvas cannot be expanded anymore.";

var Widget = {
	_widget: null,
	_setting: {preset_index:1,width:400, height:100},	
	_cell_list: [],
	_photo_index: 1,
	_focused_cell: null,
	_mydrag : null,
	_dragging: null,
	_mode : "order",
	_antes_setting: {preset_index:null, order:''},
	_initialized: 0,
	_tmpFileId:null,
	_platform:null,
	_profile:null,
	_sig_session:null,

	init: function(tmpFileId,platform,profile,sig_session) {
		this._tmpFileId = tmpFileId;
		this._platform = platform;
		this._profile = profile;
		this._sig_session = sig_session;
		this._widget = $("widget");

		this._onMouseDown = this.onMouseDown.bindAsEventListener(this);
		this._widget.observe("mousedown", this._onMouseDown);

		this._onClickCell = this.onClickCell.bindAsEventListener(this);

		var rc = this._widget.getObjectScreenRect();
		
		if(this._platform!=0)
			this.loadSetting();
		else{
			hideThrobber();
			}
	},

	initCanvas: function() {
		this.setHeight(this._setting.height);
	},

	setHeight: function(h) {
		maxHeight=1500;
		if(this._platform==1)
			maxHeight=1000;
		if(h>maxHeight)
			h=maxHeight;
		this._setting.height = h;
		this._widget.setStyle({height: this._setting.height + "px"});

		var rc = this._widget.getObjectScreenRect();
	},

	clearAll: function() {
		if (!confirm(MSG_CLEARALL)) {
			return;
		}

		this.clearFocus();

		this._photo_index = 1;
		
		var cells = this._widget.getElementsBySelector(".cell");
		cells.each(function(e) {
			e.remove();
		});
		
		var cells = $("photos_selected").getElementsBySelector(".photo_selected");
		cells.each(function(e) {
			e.remove();
		});
		
		$("wrapper_photos_selected").hide();
		this.setHeight(100);
	},

	loadSetting: function() {
		// todo temp
		var options = {
			method: 'get',
			postBody: "platform=" + this._platform + "&profile=" + this._profile,
			onSuccess: Widget.onLoadSuccess.bind(this)
		}

		Ajax.callApi("load", options);
		
	},

	onLoadSuccess: function(transport) {
		var rsp;
		rsp=transport.responseText.evalJSON();		
		if (rsp.statusCode != "ok") {
			hideThrobber();
			this.InitCanvas();
			return;
		}
		
		
		this._setting = rsp.setting;
		if (!this._setting.height) {
			this._setting.width = 400;
			this._setting.height = 100;
		}

		this.initCanvas();		
		this.update();
		hideThrobber();
	},
			
	update: function() {
		this._widget.setStyle({width: this._setting.width,  height: this._setting.height})
		
		this._setting.cell_list.each(function(info) {
			Widget.makeCell(info.url, info.cell[0] || 0, info.cell[1] || 0, info.cell[2], info.cell[3]);
		});
		this.setPreset(this._setting.preset_index);
		Sortable.create('widget',{tag:'div', containment:'widget',  overlap: 'horizontal',  constraint: false, only:'cell', onUpdate:updateOrder});
	},

	makeCell: function(url, x, y, w, h) {
		var index = this._photo_index++;
		
		var new_cell = $("cell_sample").cloneNode(true);
		new_cell.id = "cell_"+index;
		new_cell.setObjectRect(x,y,w,h);
		
		$("widget").appendChild(new_cell);
		var photo_container = new_cell.getElementsBySelector(".photo_container")[0]
		var html = "<img src='"+url+"' onload='Widget.onLoadPhoto(this)' onerror='Widget.onErrorPhoto(this)' class='photo' style='visibility:hidden;' onmouseover='Widget.onRollOver(this)' onmouseout='Widget.onRollOut(this)'/>";
		photo_container.innerHTML = html;
		Event.observe(new_cell, "click", this._onClickCell);
		
		this._cell_list.push(new_cell);
		Carrousel.go(0);

		return new_cell;
	},

	addPhoto: function(url, x, y, w, h) {
		var className = "";
		if (arguments.length < 4 ) {
			var rc = this._widget.getObjectRect();

			w = 0;
			h = 0;
			x = (rc.getWidth()-w)/2;
			y = (rc.getHeight()-h)/2;
			className = "first_load";
		}
		
		var new_cell = this.makeCell(url, x, y, w, h);
		new_cell.getElementsBySelector(".photo_container img")[0].addClassName(className);
		Sortable.create('widget',{tag:'div', containment:'widget', constraint: false, only:'cell', onUpdate:updateOrder});
		return new_cell;
	},

	onRemovePhoto: function(ev) {
		var element = Event.element(ev);
		/*alert(element.id)
		while(1) {
			if (element.hasClassName("photo_selremove")) {
				break;
			}
			element = $(element.parentNode);
		}
		Event.stop(ev);*/
		
		var index = parseInt(element.id.substr(15));
		var removing_cell = $("cell_"+index);

		Widget._cell_list = Widget._cell_list.without(removing_cell);
		removing_cell.remove();
		Sortable.create('widget',{tag:'div', containment:'widget', constraint: false, only:'cell', onUpdate:updateOrder});
		Widget.setPreset(Widget._setting.preset_index);
		Carrousel.go(0);
	},

	onLoadPhoto: function(img) {
		img = $(img);		
		if (!img.naturalWidth) {
			img.naturalWidth = img.width;
			img.naturalHeight = img.height;
		}

		var cell = $(img.parentNode.parentNode);

		if (img.hasClassName("first_load")) {
			Widget.autoFix(cell);
		}

		Widget.updateCell(cell);
	},

	onErrorPhoto: function(img) {
		
	},

	autoFix: function(cell) {		
		cell = $(cell);		

		var img = cell.getElementsBySelector(".photo_container img")[0];		
		if (!img.naturalWidth) {
			img.naturalWidth = img.width;
			img.naturalHeight = img.height;
			if(!img.naturalWidth)
				return
		}

		var rc = cell.getObjectRect();
		var box = Widget.calcFitImageBox(img.naturalWidth, img.naturalHeight, cell.getWidth()-2, cell.getHeight()-2)
		rc.left += box.x; 
		rc.top += box.y;
		rc.right = rc.left+box.w;
		rc.bottom = rc.top+box.h;

		cell.setObjectRect(rc);
	},

	calcFitImageBox: function (iw, ih, vw, vh) {
		var wr = vw/iw;
		var hr = vh/ih;

		var ratio = (wr<hr)?wr:hr;
		var w = ratio*iw;
		var h = ratio*ih;

		return {x: (vw-w)/2, y: (vh-h)/2, w: w, h: h};
	},

 	redondea: function(sVal, nDec){
		var n = parseFloat(sVal);
		var s;
		n = Math.round(n * Math.pow(10, nDec)) / Math.pow(10, nDec);
		s=String(n);
		if(s.indexOf(".")==-1)
			s = String(n) + "." + String(Math.pow(10, nDec)).substr(1);
		else	
			s +="0000000000"; 
		s = s.substr(0, s.indexOf(".") + nDec + 1);
		return s;
   }, 
   
	calcPhotoSize: function(iw, ih, vw, vh) {
		// box를 꽉 채우도록 계산. 비율이 큰쪽이 잘려보인다.

		var wr = vw/iw;
		var hr = vh/ih;

		var ratio = (wr>hr)?wr:hr;
		
		//var w = this.redondea(ratio*iw,3);
		//var h = this.redondea(ratio*ih,3);
		var w = Math.round(ratio*iw);
		var h = Math.round(ratio*ih);

		return {x: (vw-w)/2, y: (vh-h)/2, w: w, h: h};
	},

	setFocus: function(cell) {
		this.clearFocus();
		this._focused_cell = cell;

		this._focused_cell.removeClassName("rollover");
		this._focused_cell.addClassName("selected");

		var rc = this._focused_cell.getObjectScreenRect();
		var size = getPageSize();
		setScrollPos((rc.getWidth()-size.w)/2+rc.left, (rc.getHeight()-size.h)/2+rc.top);
	},

	clearFocus: function() {
		if (!this._focused_cell) {
			return;
		}

		this._focused_cell.removeClassName("selected");
		this._focused_cell = null;
	},

	onRollOver: function(img) {
		if (0 && this._focused_cell) {
			return;
		}

		if (img.parentNode.parentNode == this._focused_cell) {
			return;
		}
		Element.addClassName(img.parentNode.parentNode, "rollover");
	},

	onRollOut: function(img) {
		Element.removeClassName(img.parentNode.parentNode, "rollover");
	},

	onMouseDown: function(ev) {
		this.clearFocus();
	},

	onMouseUp: function(ev) {

	}, 

	onClickCell: function(ev) {
		var element = Event.element(ev);
		while(1) {
			if (element.hasClassName("cell")) {
				break;
			}

			element = $(element.parentNode);
		}

		this.setFocus(element);
		Event.stop(ev);
		if(this._mode=="drag"){						
			this.setDragg(element);
		}
		if(this._mode=="adjust"){						
			this.updateCell(element);
		}
	},

	onClick_AddPhoto: function() {
		setScrollPos(0,10000);
	},

	updateCell: function(cell,w,h,t,l) {
		var container = cell.getElementsBySelector(".photo_container")[0];
		var img = cell.getElementsBySelector("img")[0];

		var rc = cell.getObjectRect(rc);
		rc.offset(-rc.left, -rc.top);
		container.setObjectRect(rc);

		if (!img.naturalWidth || !img.naturalHeight) {
			img.naturalWidth = img.width;
			img.naturalHeight = img.height;
			if (!img.naturalWidth || !img.naturalHeight) {
				return;
			}
		}

		var box = Widget.calcPhotoSize(img.naturalWidth, img.naturalHeight, container.offsetWidth, container.offsetHeight); // except border size
		//alert(box.w + "   " + parseInt(w) + "   " + box.h + "   " + parseInt(h));
		//alert(box.w + "   " + w + "   " + box.h + "   " + h);
		//if((box.w==this.redondea(w,3))&&(box.h==this.redondea(h,3))){
		if((box.w==parseInt(w))&&(box.h==parseInt(h))){
			img.setStyle({left: l+"px", top:t+"px", width:box.w+"px", height: box.h+"px", visibility: "inherit"});
			}
		else
			img.setStyle({left: box.x+"px", top:box.y+"px", width:box.w+"px", height: box.h+"px", visibility: "inherit"});
		
	},

	checkCanvas: function() {
		var isValid = true;
		var h = this._setting.height;
		var cells = this._widget.getElementsBySelector(".cell");
		
		cells.each(function(cell) {
			var rc = cell.getObjectRect();
			if (rc.bottom >= h) {
				isValid = false;
				throw $break;
			}
		});

		return isValid;
	},
	
	save: function() {
		showThrobber("Saving...");

		var cells = this._widget.getElementsBySelector(".cell");
		this._setting.cell_list = cells.map(function(cell) {
			var index = parseInt(cell.id.substr(5));
			var rc = cell.getObjectRect();
			var img = cell.getElementsBySelector("img")[0];
			var irc = img.getObjectRect();

			return {type:"photo", url: img.src, cell: [rc.getWidth(), rc.getHeight()], img:[ irc.left, irc.top, irc.getWidth(), irc.getHeight()]};
		});
		
		var options = {
			method: 'post',
			postBody: "tmpFileId=" + this._tmpFileId + "&platform=" + this._platform + "&profile=" + this._profile + "&gallery_data="+escape(Object.toJSON(this._setting)),
			onComplete: Widget.onSaveSuccess
		}
		Ajax.callApi("save", options);

	},

	onSaveSuccess: function(transport) {				
		hideThrobber();
		rsp=transport.responseText.evalJSON();
		
		if(rsp.statusCode="ok"){
			if(parseInt(Widget._platform)==0){
				Lightview.show({
					  href: 'show_code.php?tmpFileId=' + Widget._tmpFileId,
					  rel: 'iframe',
					  options: {
							width:450,
							height:365,
							topclose: true,
							overlayClose: false
					  }
					});
			}
			else{
				switch(Widget._platform){
					case 1:{
						Lightview.show({
						  href: '#msg_ok',
						  rel: 'inline',
						  options: {
								width:300,
								height:50,
								topclose: true
						  }
						});
						break;
						}
					case 2:{
						top.location.href="http://apps.facebook.com/dundoo_collage/update_ok.php";
						break;
						}
					case 3:{
						top.location.href="http://widgets.friendster.com/dundoo_collage/update_ok.php";
						break;
						}
					}
			}
		}
	},
	
	sortable: function() {
		$("btn_move").addClassName("selected");
		$("btn_hand").removeClassName("selected");
		$("btn_adjust").removeClassName("selected");
		
		var cells = this._widget.getElementsBySelector(".cell");
		this._setting.cell_list = cells.map(function(cell) {			
			cell.removeClassName("dragable");
			});
		
		if(this._mydrag){
			this._mydrag.destroy();		
			this.dragging=null;
		}
		Sortable.create('widget',{tag:'div', containment:'widget',  overlap: 'horizontal',  constraint: false, only:'cell', onUpdate:updateOrder});
		this._mode="order";
	},
	
	draggable: function() {		
		$("btn_hand").addClassName("selected");
		$("btn_move").removeClassName("selected");
		$("btn_adjust").removeClassName("selected");
		
		var cells = this._widget.getElementsBySelector(".cell");
		this._setting.cell_list = cells.map(function(cell) {						
			cell.addClassName("dragable");
			});
		
		Sortable.destroy('widget');
		if (this._focused_cell) {
			this.setDragg(this._focused_cell);
		}
		this._mode="drag";
	},
	
	setDragg: function(element){
		if(this.dragging!=element){
		   if(this._mydrag)
		   	this._mydrag.destroy();
		
			var img = element.getElementsBySelector("img")[0];
			Widget._mydrag = new Draggable(img);
			this.dragging=element;
			}
		},
		
	adjustable: function() {			
		$("btn_adjust").addClassName("selected");
		$("btn_move").removeClassName("selected");
		$("btn_hand").removeClassName("selected");
		
		var cells = this._widget.getElementsBySelector(".cell");
		this._setting.cell_list = cells.map(function(cell) {			
			cell.removeClassName("dragable");
			Widget.updateCell(cell);
			});
		
		if(this._mydrag){
			this._mydrag.destroy();		
			this.dragging=null;
		}
		
		Sortable.destroy('widget');
		if (this._focused_cell) {
			this.setDragg(this._focused_cell);
		}
		this._mode="adjust";
	},
	
	setPreset: function(preset_index, initialize ) {
		this._setting.preset_index = preset_index;
		
		//check order
		var cells = this._widget.getElementsBySelector(".cell");
		var order="";		
		this._setting.cell_list = cells.map(function(cell) {
			var index = parseInt(cell.id.substr(5));
			order+=index;
			});
		
		//check 
		if(initialize)
			this._initialized++;

		if(this._initialized>1){			
			if((this._antes_setting.preset_index==this._setting.preset_index)&&(order==this._antes_setting.order))
				return;
		}
			
		var preset_data = Preset.DATA[preset_index];

		var cells = this._widget.getElementsBySelector(".cell");
		var cell_index = 0;
		
		var oy = 0;
		var isContinue = true;
		while(isContinue) {
			for(var i = 0; i<preset_data.length; i++) {
				var data = preset_data[i];
				var w = data[2];
				var h = data[3];
			
				var x_repeat = data[4] || 1;
				var y_repeat = data[5] || 1;

				try
				{
					for(var k=0;k<y_repeat;k++) {
						var y = data[1] + h*k + oy;
						
						for(var j=0;j<x_repeat;j++) {
							var x = data[0] + w*j;
							var cell = cells[cell_index++];							
							
							if (!cell) {								
								throw "end";
							}
							
							var img = cell.getElementsBySelector("img")[0];
							//cell.setObjectRect(0, 0, w*400-2, h*400-2);
							if( typeof( window.innerWidth ) != 'number' ) { //IE
								switch(preset_index){
								case 3:
									cell.setObjectRect(0, 0, w*400-2, h*397);
									break;
								case 9:
									cell.setObjectRect(0, 0, w*400-2, h*400);
									break;
								default:
									cell.setObjectRect(0, 0, w*400-2, h*400-2);
								}
							}
							else
								cell.setObjectRect(0, 0, w*400-2, h*400-2); //FF
							this.updateCell(cell,img.style.width,img.style.height,img.style.top,img.style.left);
						}					
					}			
				}
				catch (e)
				{
					if (e == "end") {
						isContinue = false;
						break;
					}
				}
			}

			oy += 1;
			
			var max_h = 0;
			var cells = this._widget.getElementsBySelector(".cell");
			
			cells.each(function(cell) {
				var rc = cell.getObjectRect();
				if (rc.bottom >= max_h) {
					max_h = rc.bottom;
				}
			});
			
			var widget_h = Math.max(max_h, 100);
			this.setHeight(widget_h);
			this._widget.setStyle({height:this._setting.height+"px"});				
			
		}
	
		this._antes_setting.preset_index=this._setting.preset_index;
		this._antes_setting.order = order;
	},
	
	shuffle: function() {
		var cells = this._widget.getElementsBySelector(".cell");
		numPosibilidades=this._setting.cell_list.length;
		
		var	ids=[];
		var	urls=[];
		this._setting.cell_list = cells.map(function(cell) {
			ids.push(cell.id);
			var img = cell.getElementsBySelector("img")[0];
			urls.push(img.src);
			});
		
		 var i = ids.length;
		 if (i > 0) {
			 while (--i) {
			  var j = Math.floor(Math.random()*(i+1));
			  var tmp1 = ids[i];
			  var tmp2 = ids[j];
			  ids[i] = tmp2;
			  ids[j] = tmp1;
			  var tmp3 = urls[i];
			  var tmp4 = urls[j];
			  urls[i] = tmp4;
			  urls[j] = tmp3;
			 }
		 }
		
		i=0;
		this._setting.cell_list = cells.map(function(cell) {
			cell.id=ids[i];
			var img = cell.getElementsBySelector("img")[0];
			img.src=urls[i++];
			//img.onload=Widget.onLoadPhoto(img);
		});
	this.setPreset(this._setting.preset_index);	
	}
}

Ajax.callApi = function(method, options) {
	
	var params = document.location.href.split("?")[1];

	var url = method+".php";
	
	return new Ajax.Request(encodeURIComponent(url)+"?"+params, options);
}