var top=0;
var left=0;
var src="";
var textId=0;
$(document).ready(function(){
	$("img.special","#createLeftPanel").draggable({ revert: 'invalid',helper:"clone",opacity: 0.6,zIndex:999 });
	$("#collageZone").droppable({
		drop: function(event, ui) {
			$("#collageZone").css("background-image","none");
			left=$(ui.helper).offset().left-$("#collageZone").offset().left;
			top=$(ui.helper).offset().top-$("#collageZone").offset().top;
			src=$(ui.draggable).attr("title");
			var img = new Image();
			img.onload=CreateDelegate(img, addNewImage);
			img.src = src;
		},
		accept: '.special' 
	});		
	
	
	$("#changeColor").ColorPicker({
		color: '#000000',
		onShow: function (cp) {
			$(cp).fadeIn(500);
			return false;
		},
		onHide: function (cp) {
			$(cp).fadeOut(500);
			return false;
		},
		onChange: function (hsb, hex, rgb) {	
			$('.active-collage-text').css('color', '#'+hex);
		}
	});
	
	$('#mycarousel').jcarousel({
        visible: 4
    });
	
	if($("#collageId").val()!="undefined" && $("#collageId").val()!=""){
	
		$(".collage-text","#collageZone").each(
			function(){
				$(this).draggable({ containment: '#collageZone',zIndex:$(this).css("z-index") });
				$(this).draggable( 'disable' );
				$(this).mousedown(function(){
					showOptions("text");
					if(!$(this).hasClass("active-collage-text")){
						prepareItems();
						$(this).addClass("active-collage-text");
						$(this).draggable( 'enable' );
						$(this).addClass("active-collage-container");	
					}
				});
			}
		);
		
		$(".collage-image","#collageZone").each(
			function(){
				$(this).resizable({ aspectRatio:true,handles: "s,w,e,n,sw,se,ne,nw"}).parent().draggable({ containment: '#collageZone',zIndex:$(this).css("z-index") });
				$(this).resizable( 'disable' ).parent().draggable( 'disable' );
				$(this).parent().addClass("collage-container");
				$(this).parent().css('z-index', $(this).css("z-index"));
				$(this).mousedown(function(){
					showOptions("image");
					if(!$(this).hasClass("active-collage-img")){
						prepareItems();
						$(this).addClass("active-collage-img");
						$(this).resizable( 'enable' ).parent().draggable( 'enable' );
						$(this).parent().addClass("active-collage-container");				
					}
				});
			}
		);
		$("#collageZone").css("background-image","none");	
	}
});

function CreateDelegate(contextObject, delegateMethod){
    return function(){return delegateMethod.apply(contextObject, arguments);}
}

function deleteFromBin(id){
	if(id!=0){
		$(".special",$("#delete-"+id).parent()).draggable("destroy");
		$("#delete-"+id).parent().fadeOut(function (){ $("#delete-"+id).parent().remove() });
	}else{
		$(".special").parent().draggable("destroy");
		$(".special").parent().fadeOut(function (){ $(".special").parent().remove() });
	}
	$.post("ajax/deleteFromBin.php", { imageId: id },
		function(data){
			$.growlUI('Conrfirmation', 'Image(s) deleted');
		}
	);
}

function tweet(uid){
	var text="http://twitter.com/home/?status="+escape("Beaker Collage - http://beaker.me/"+uid);
	window.open(text, '_blank');
}

function showOptions(mode){
	$("#makeBackground").show();
	$("#makeForeground").show();
	$("#deleteItem").show();
	$("#makeBackground").show();
	if(mode=="text"){
		$("#increaseFont").show();
		$("#decreaseFont").show();
		$("#changeText").show();
		$("#changeColor").show();
	}else{
		$("#increaseFont").hide();
		$("#decreaseFont").hide();
		$("#changeText").hide();
		$("#changeColor").hide();
	}	
}

function addText(){
	$("body").append("<div id='dialog' title='Add/update text' style='display:none;'><br /><input type='text' id='newText' value='Enter your text here' style='width:250px;' /></div>");
	$("#dialog").dialog({
		bgiframe: true,
		resizable: false,
		height:140,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Add/Update text': function() {
				if($("#newText").val()==""){
					$.growlUI('Notice', 'Text cannot be empty!');
				}else{
					insertText($("#newText").val());
					$.growlUI('Conrfirmation', 'Text added!');
				}
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function(event, ui) {
			$("#dialog").remove();
		}
	});
}

function insertText(text){	
	$("#collageZone").css("background-image","none");
	showOptions("text");
	$("#collageZone").append("<span title='na' id='text-"+textId+"' style='z-index:1;left:10px;top:10px;position:absolute;font-size:12pt;color:#000000;' name='12pt' class='new collageItem collage-text collage-container'>"+text+"</span>");
	$(".new","#collageZone").draggable({ containment: '#collageZone',zIndex:1 });
	$(".new","#collageZone").draggable( 'disable' );
	$(".new","#collageZone").mousedown(function(){
		showOptions("text");
		if(!$(this).hasClass("active-collage-text")){
			prepareItems();
			$(this).addClass("active-collage-text");
			$(this).draggable( 'enable' );
			$(this).addClass("active-collage-container");	
		}
	});
	prepareItems();
	$(".new","#collageZone").addClass("active-collage-text");
	$(".new","#collageZone").draggable( 'enable' );
	$(".new","#collageZone").addClass("active-collage-container");
	
	var maxZindex=1;
	$(".collageItem","#collageZone").each(
		function(){
			if($(this).css('z-index')>maxZindex)maxZindex=$(this).css('z-index');
		}
	);
	var newZindex=parseInt(maxZindex)+1;
	$(".new","#collageZone").draggable('option', 'zIndex', newZindex);
	$(".new","#collageZone").css('z-index', newZindex);
	$(".new","#collageZone").removeClass("new");
	textId++;
}

function makeForeground(){
	var maxZindex=1;
	$(".collageItem","#collageZone").each(
		function(){
			if($(this).css('z-index')>maxZindex)maxZindex=$(this).css('z-index');
		}
	);
	var newZindex=parseInt(maxZindex)+1;
	$(".active-collage-img","#collageZone").parent().draggable('option', 'zIndex', newZindex);
	$(".active-collage-img","#collageZone").parent().css('z-index', newZindex);
	$(".active-collage-img","#collageZone").css('z-index', newZindex);
	
	$(".active-collage-text","#collageZone").draggable('option', 'zIndex', newZindex);
	$(".active-collage-text","#collageZone").css('z-index', newZindex);
}	

function makeBackground(){
	var minZindex=0;
	$(".collageItem","#collageZone").each(
		function(){
			if($(this).css('z-index')<minZindex)minZindex=$(this).css('z-index');
		}
	);
	var newZindex=parseInt(minZindex)-1;
	$(".active-collage-img","#collageZone").parent().draggable('option', 'zIndex', newZindex);
	$(".active-collage-img","#collageZone").parent().css('z-index', newZindex);
	$(".active-collage-img","#collageZone").css('z-index', newZindex);
	
	$(".active-collage-text","#collageZone").draggable('option', 'zIndex', newZindex);
	$(".active-collage-text","#collageZone").css('z-index', newZindex);
}	

function addNewImage(){
	showOptions("image");
	$("#collageZone").append("<img src='"+src+"' style='z-index:1;left:"+left+"px;top:"+top+"px;position:absolute;width:"+this.width+"px;height:"+this.height+"px' class='new collageItem collage-image' />");		
	$(".new","#collageZone").resizable({ aspectRatio:true,handles: "s,w,e,n,sw,se,ne,nw"}).parent().draggable({ containment: '#collageZone',zIndex:1 });
	$(".new","#collageZone").resizable( 'disable' ).parent().draggable( 'disable' );
	$(".new","#collageZone").parent().addClass("collage-container");
	$(".new","#collageZone").mousedown(function(){
		showOptions("image");
		if(!$(this).hasClass("active-collage-img")){
			prepareItems();
			$(this).addClass("active-collage-img");
			$(this).resizable( 'enable' ).parent().draggable( 'enable' );
			$(this).parent().addClass("active-collage-container");				
		}
	});
	prepareItems();
	$(".new","#collageZone").addClass("active-collage-img");
	$(".new","#collageZone").resizable( 'enable' ).parent().draggable( 'enable' );
	$(".new","#collageZone").parent().addClass("active-collage-container");
	
	var maxZindex=1;
	$(".collageItem","#collageZone").each(
		function(){
			if($(this).parent().css('z-index')>maxZindex)maxZindex=$(this).parent().css('z-index');
		}
	);
	var newZindex=parseInt(maxZindex)+1;
	$(".new","#collageZone").parent().draggable('option', 'zIndex', newZindex);
	$(".new","#collageZone").parent().css('z-index', newZindex);
	$(".new","#collageZone").css('z-index', newZindex);
	$(".new","#collageZone").removeClass("new");
}

function prepareItems(){
	$(".active-collage-img","#collageZone").resizable( 'disable' ).draggable( 'disable' );
	$(".active-collage-img","#collageZone").parent().removeClass("active-collage-container");
	$(".active-collage-img","#collageZone").removeClass("active-collage-img");
	
	$(".active-collage-text","#collageZone").draggable( 'disable' );
	$(".active-collage-text","#collageZone").removeClass("active-collage-container");
	$(".active-collage-text","#collageZone").removeClass("active-collage-text");
}

function deleteItem(){
	$(".active-collage-img").resizable( 'destroy' ).draggable( 'destroy' ).fadeOut(function (){ $(this).remove() })
	$(".active-collage-text").draggable( 'destroy' ).fadeOut(function (){ $(this).remove() })
	var totalLeft=0;
	$(".collageItem","#collageZone").each(
		function(){
			totalLeft++;
		}
	);
	if(totalLeft==1){
		$("#collageZone").css("background-image","url(images/collage_back.png)");
		$("#makeBackground").hide();
		$("#makeForeground").hide();
		$("#deleteItem").hide();
		$("#makeBackground").hide();
		$("#increaseFont").hide();
		$("#decreaseFont").hide();
		$("#changeText").hide();
	}
	$.growlUI('Conrfirmation', 'Item deleted');
}

function clearCollage(notify){
	if(notify == null)notify=true;
	$("img.collageItem","#collageZone").resizable( 'destroy' ).draggable( 'destroy' ).fadeOut(function (){ $(this).remove() })
	$("span.collageItem").draggable( 'destroy' ).fadeOut(function (){ $(this).remove() })
	$("#collageZone").css("background-image","url(images/collage_back.png)");
	$("#makeBackground").hide();
	$("#makeForeground").hide();
	$("#deleteItem").hide();
	$("#makeBackground").hide();
	$("#increaseFont").hide();
	$("#decreaseFont").hide();
	$("#changeText").hide();
	if(notify)$.growlUI('Conrfirmation', 'Collage cleared');
}

function changeText(){
	var currentText=$(".active-collage-text","#collageZone").html();
	$("body").append("<div id='dialog' title='Add/update text' style='display:none;'><br /><input type='text' id='newText' value='"+currentText+"' style='width:250px;' /></div>");
	$("#dialog").dialog({
		bgiframe: true,
		resizable: false,
		height:140,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Add/Update text': function() {
				if($("#newText").val()==""){
					$.growlUI('Notice', 'Text cannot be empty!');
				}else{
					updateText($("#newText").val());
					$.growlUI('Conrfirmation', 'Text updated!');
				}
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function(event, ui) {
			$("#dialog").remove();
		}
	});
}

function updateText(text){
	$(".active-collage-text","#collageZone").html(text);
}

function increaseFont(){
	var oldFont=$(".active-collage-text","#collageZone").attr("name");
	oldFont=parseInt(oldFont.replace("pt", ""));
	var newFont=oldFont+2;
	$(".active-collage-text","#collageZone").css("font-size",newFont+"pt");
	$(".active-collage-text","#collageZone").attr("name",newFont+"pt");
}	

function decreaseFont(){
	var oldFont=$(".active-collage-text","#collageZone").attr("name");
	oldFont=parseInt(oldFont.replace("pt", ""));
	var newFont=oldFont-2;
	$(".active-collage-text","#collageZone").css("font-size",newFont+"pt");
	$(".active-collage-text","#collageZone").attr("name",newFont+"pt");
}	

function deleteCollage(){
	$.growlUI('Conrfirmation', 'Collage deleted');
	clearCollage(false);
	$("#createBottom").html("<a class='large awesome' onclick='saveCollage();'>Save this collage</a> <a class='large magenta awesome' onclick='clearCollage();'>Clear the collage area</a>");
	$.post("ajax/deleteCollage.php", { collageId: $("#collageId").val() },
		function(data){
			
		}
	);
	$("#collageId").val("");
}

function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}


function saveCollage(){
	var items="";
	$(".collageItem","#collageZone").each(
		function(){
			var x=Math.round($(this).offset().left-$("#collageZone").offset().left);
			var y=Math.round($(this).offset().top-$("#collageZone").offset().top);
			var color="na";
			var font="na";
			var text="na"
			var src="na"
			if($(this).hasClass("collage-text")){
				color=$(this).css("color");
				if(color.indexOf("rgb")!=-1){
					color=color.substr(4,color.length);
					color=color.substr(0,color.length-1);
					var colorItems=color.split(","); 
					color=RGBtoHex(colorItems[0],colorItems[1],colorItems[2]);
				}
				color="#"+color;
				font=$(this).attr("name");
				font=parseInt(font.replace("pt", ""));
				text=$(this).html();
			}else{
				src=$(this).attr("src")
			}
			items+=","+src+":"+$(this).css("z-index")+":"+x+":"+y+":"+$(this).width()+":"+$(this).height()+":"+color+":"+font+":"+text;
		}
	); 
	items=items.substr(1);
	$("#createBottom").html("<img src='images/ajax.gif' />");
	var collageId=$("#collageId").val();
	$.post("ajax/saveCollage.php", { items: items,collageId: collageId },
		function(data){
			collageData=data.split(":"); 
			$("#collageId").val(collageData[0]);
			$("#createBottom").html("<div id='collageLink'>Link to your collage: <a href='"+collageData[1]+"'>http://beaker.me/"+collageData[1]+"</a></div><a class='large awesome' onclick='saveCollage();'>Update collage</a>&nbsp;<a class='large orange awesome' onclick='tweet(\""+collageData[1]+"\");'>Tweet this collage</a>&nbsp;<a class='large magenta awesome' onclick='clearCollage();'>Clear the collage area</a>&nbsp;<a class='large red awesome' onclick='deleteCollage();'>Delete collage</a>&nbsp;<a href='index.php?section=create' class='large red awesome'>New collage</a>");
			$.growlUI('Conrfirmation', 'Collage saved');
		}
	);
}

function loadImages(page){
	$("#bin").html("<img src='images/ajax.gif' />");
	$.post("ajax/loadImages.php", { page: page },
		function(data){
			$("#bin").html(data);
			$("img.special","#createLeftPanel").draggable({ revert: 'invalid',helper:"clone",opacity: 0.6,zIndex:999 });
		}
	);
}