(function(){
/*
 	Class: LightBoxDialog
 	Description:
 	The base LightBoxDialog class used for generic user interaction
 */
function LightBoxDialog() 
{ 
	this.p_config = {};
	this.p_isShowing = false;

	this.htmlObj = YUIDom.get("itemdetail_panel");
	this.overlayObj = YUIDom.get( "overlay_lb" );
	this.item = null;

// close LightBox button on the top 
	var buttonClose = document.getElementById("sb_dialog_buttonclose");
	if( buttonClose )
		YUIEvent.addListener( buttonClose, "click", this.destroy, this, true );
	
	var rob = document.getElementById("lightbox_returntobox");
	if( rob ) YUIEvent.addListener( rob, "click", this.returnToBox, this, true );

	var bfb = document.getElementById("itemdetail_bfb");
	if( bfb )
		YUIEvent.addListener( bfb, "click", this.destroy, this, true );


//confirmation dialog	

// show delete item confirmation dialog 
	var lbDelete = document.getElementById("lightboxdelete");
	YUIEvent.addListener( lbDelete, "click", this.confirmDeleteItem, this, true );
// delete item 
	var lbDeleteItem = document.getElementById("lightbox_deleteitem");
	YUIEvent.addListener( lbDeleteItem, "click", this.deleteItem, this, true );
// cancel delete item 
	var lbCancelDeleteItem = document.getElementById("lightbox_canceldeleteitem");
	YUIEvent.addListener( lbCancelDeleteItem, "click", this.cancelDeleteItem, this, true );

//Title

// cancel title edit 
	var lbCancelTitleEdit = document.getElementById("lb_cancel_title_edit");
	YUIEvent.addListener( lbCancelTitleEdit, "click", cancelTitleEdit, this, true );
// save title edit 
	var lbSaveTitleEdit = document.getElementById("lb_save_title_edit");
	YUIEvent.addListener( lbSaveTitleEdit, "click", saveTitleEdit, this, true );
// do title edit 
	var lbTitleEdit = document.getElementById("lb_title_edit");
	YUIEvent.addListener( lbTitleEdit, "click", titleEdit, this, true );

	//Configure addthis
	var addthis = YUIDom.get("itemdetails_addthis");
	if( addthis )
		YUIEvent.addListener( addthis, "mouseover", configureAddThis, this, false );

	var editbutton = YUIDom.get("itemdetail_editimage_link");
	if( editbutton )
		YUIEvent.addListener( editbutton, "click", this.editImage, this, true );
	
//Comments	
	var lbAddComment = document.getElementById("lightbox_addcomment_button");
	YUIEvent.addListener( lbAddComment, "click", addComment, this, true );


	//var lbCommentbox = document.getElementById("commentbox");
	//YUIEvent.addListener( lbCommentbox, "keyup", commentboxTextChanged, this, false );

	this.contentHtmlObj = null;
}

LightBoxDialog.prototype.toString = function() { return "[SB.ui.LightBoxDialog]"; }

//Group: Basic Methods 
/*
 	Function: setConfig
 	Establishes the basic setup for the LightBoxDialog.
 	
 	inConfig - A configuration array (key/value)
 
 	Configuration Array Options:
 	id - the id of the div to use as a template (default: sb_ui_dialog)
 	content - the id of a DOMElement to use as the body of the dialog (default: none)
 	buttons - an array of SB.ui.Component.Buttons (default: none)
 	x - absolute horizontal position, or "center" (default: center)
 	y - absolute vertical position, or "center" (default: center)
 	refpoint - an array { x:"", y:"" } to position dialog to point at a specific location.  Automatically adds a pointer image. (default:none)
 	refid - the id of a DOMElement to point the dialog at.  Automatically adds a pointer image.  Overrides refpoint, if used together.  (default: none)
 	type - the LightBoxDialog type ( Alert, Confirm, Critical, or Form ) (default:Form)
 */
LightBoxDialog.prototype.setConfig =  function( inConfig )
{
	this.p_config = inConfig;
	this.item = inConfig.item;
	this.item.id = this.item.item_id;

	SBui.Stage.sendBeacon();

	if( inConfig.from )
		this.from = inConfig.from;
	else
		this.from = 0;

	if( this.item.box_username != window["sb_username"] ) //Hide stuff if item is not owned by current user
	{
		YUIDom.getElementsByClassName("tag_edit","div", this.htmlObj, 
			function(el) { el.style.display="none"; }); 
	}

	if( YUIDom.get("itemdetail_tabview") )
	{
		var textdata_wrapper = YUIDom.get("itemdetail_text_data");
		if( textdata_wrapper )
		{
			textdata_wrapper.innerHTML = this.item.text_data;
		}

		var tabView = new YAHOO.widget.TabView('itemdetail_tabview', { orientation:"top"} );
	}
	

	var nextimage = YUIDom.get("itemdetail_next_img");
	var previmage = YUIDom.get("itemdetail_prev_img");

	if( nextimage && previmage )
	{
		nextimage.src="http://"+window["sb_static_image_host"]+"/images/circle_load.gif";
		nextimage.width = nextimage.height = 32;
		previmage.src="http://"+window["sb_static_image_host"]+"/images/circle_load.gif";
		previmage.width = previmage.height = 32;
	}


	if( this.from == 1 )
	{
		var arr = YUIDom.getElementsByClassName("itemdetail_returntobox_content_title","div",this.htmlObj);
		if( arr[0] ) arr[0].innerHTML = SBtranslation[2];	
		
		YUIDom.getElementsByClassName("itemdetail_boxnavigate","div",this.htmlObj,
			function(el) { el.style.display = "none"; } );

		var preview = YUIDom.get("itemdetail_boxpreview");
		if( preview ) preview.style.height = "25px";

		var bdetail = YUIDom.get("itemdetail_boxdetails");
		if( bdetail ) bdetail.style.display = "none";

	}
	else if( this.from == 2 )
	{
		var arr = YUIDom.getElementsByClassName("itemdetail_returntobox_content_title","div",this.htmlObj);

		if( arr[0] ) arr[0].innerHTML = SBtranslation[3];	

		var preview = YUIDom.get("itemdetail_boxpreview");
		if( preview ) preview.style.height = "25px";

		var bdetail = YUIDom.get("itemdetail_boxdetails");
		if( bdetail ) bdetail.style.display = "none";

	}
	else
	{
		var arr = YUIDom.getElementsByClassName("itemdetail_returntobox_content_title","div",this.htmlObj);
		if( arr[0] ) arr[0].innerHTML = SBtranslation[1];	

		YUIDom.getElementsByClassName("itemdetail_boxnavigate","div",this.htmlObj,
			function(el) { el.style.display = "block"; } );

		var preview = YUIDom.get("itemdetail_boxpreview");
		if( preview ) preview.style.height = "198px";

		var bdetail = YUIDom.get("itemdetail_boxdetails");
		if( bdetail ) bdetail.style.display = "block";

	}

	if( this.item.box )
	{
		this.boxOwner = inConfig.item.box.owner_username;
		var boxownerhtml = YUIDom.get("itemdetail_boxowner");
		if( boxownerhtml )
			boxownerhtml.innerHTML = this.boxOwner;

		var boxname = this.boxName  = inConfig.item.box.name;

		var boxdetail = YUIDom.get("itemdetail_boxname_detail");
		var prevcontainer = YUIDom.get("itemdetail_preview_container");
		var prevwrapper = YUIDom.get("itemdetail_preview_wrapper");

		if( !boxname.length )
		{
			if( boxdetail ) YUIDom.get("itemdetail_boxname_detail").style.display = "none";
			if( prevcontainer ) YUIDom.get("itemdetail_preview_container").style.height = "40px";
			if( prevwrapper ) YUIDom.get("itemdetail_preview_wrapper").style.display = "none";
		}
		else
		{
			if( boxdetail ) YUIDom.get("itemdetail_boxname_detail").style.display = "block";
			if( prevcontainer ) YUIDom.get("itemdetail_preview_container").style.height = "185px";
			if( prevwrapper ) YUIDom.get("itemdetail_preview_wrapper").style.display = "block";
		}

		YUIDom.getElementsByClassName("itemdetail_boxname", "span", this.htmObj, function(el) { el.innerHTML = boxname } );
		
		this.boxNumItems  = inConfig.item.box.num_items;
		var boxnumitemhtml = YUIDom.get("itemdetail_boxnumitems");
		if( boxnumitemhtml ) boxnumitemhtml.innerHTML = this.boxNumItems;

		var basicdetail = YUIDom.get("itemdetail_boxdetail_basic");
		if( basicdetail ) basicdetail.style.display = "block";
	}
	else
	{
		YUIDom.getElementsByClassName("itemdetail_boxname", "span", this.htmObj, function(el) { el.innerHTML = ""; } );
		
		if( this.from == "2" )
		{
			 YUIDom.get("itemdetail_boxname_detail").style.display = "none";
			 YUIDom.get("itemdetail_preview_container").style.height = "40px";
			 YUIDom.get("itemdetail_preview_wrapper").style.display = "none";
		}
		else
		{
			if( boxdetail ) YUIDom.get("itemdetail_boxname_detail").style.display = "block";
			if( prevcontainer ) YUIDom.get("itemdetail_preview_container").style.height = "185px";
			if( prevwrapper ) YUIDom.get("itemdetail_preview_wrapper").style.display = "block";
		}

		var basicdetail = YUIDom.get("itemdetail_boxdetail_basic");
		if( basicdetail ) basicdetail.style.display = "none";
	}

	//Scale Image for desktop
	var desktopWidth = YUIDom.getClientWidth();
	var desktopHeight = YUIDom.getClientHeight();

	//Scale Image for desktop
	var scaleFactor = 1.0;
	if( (desktopWidth - 400) < this.item.width )
	{
		scaleFactor = ((desktopWidth - 400)/this.item.width);	
	}

	if( (desktopHeight - 200) < (this.item.height * scaleFactor) )
	{
		scaleFactor = ((desktopHeight - 200)/this.item.height );
	}

	var imageWidth = (this.item.width * scaleFactor);
	var imageHeight = (this.item.height * scaleFactor);

	// image in box
	var imgObj = document.getElementById("lightboxsmimage");
	var url = this.item.url;

	if( url && url.match(/imgfile/) )
	{
		url = url.replace(/\&amp;/g,'&');
		url = "http://"+window["sb_host"]+url;
	}

	if( !url )	
	{
		url = "/item/image?id="+this.item.id;
	}

	imgObj.src = url;
	imgObj.width = imageWidth;
	imgObj.height = imageHeight;

	this.imgurl = url;

        var locale = window["sb_language"];
        if( locale == "ja" ) locale = "jp";

	var lbaddcommentsblock = YUIDom.get("lightbox_addcomments_block");
	if( lbaddcommentsblock )
		lbaddcommentsblock.style.display = "none";

        this.editlink = "http://www.pixlr.com/editor/?image="+url;
        this.editlink += "&loc=en&target=http://"+window["sb_host"]+"/edit/pixlrcallback";
        this.editlink += "&method=GET&exit=http://"+window["sb_host"]+"&loc="+locale;

	YUIEvent.addListener( window, "resize", this.resize, this, true );

	//document.getElementById("lightboxfullsize").href = "/show?id="+this.item.item_id;
	// link host 
	var link_host = this.item.link_host;
	YUIDom.getElementsByClassName("lightboxdispurl", "span", this.htmlObj, function(el){ el.innerHTML = link_host } );
	YUIDom.getElementsByClassName("lightboxdispurl_favicon", "img", this.htmlObj, function(el){ el.src = "http://"+link_host+"/favicon.ico"; } );

	var visits = this.item.num_visits;
	YUIDom.getElementsByClassName("itemdetail_stat", "span", this.htmlObj, function(el){ el.innerHTML = visits } );

	var num_comments = this.item.comments.length;
	YUIDom.getElementsByClassName("itemdetail_stat_comments", "span", this.htmlObj, function(el){ el.innerHTML = num_comments } );

	// link 
	if( typeof(this.item.link) == "undefined" )
	{
		YUIDom.get("lightbox_visit_url").style.display = "none";
		YUIDom.get("itemdetail_image_anchor").onclick = "";
	}
	else
	{
		YUIDom.get("lightbox_visit_url").style.display = "block";
		YUIDom.get("lightbox_visit_url").href = this.item.link;
		YUIDom.get("itemdetail_image_anchor").onclick = "window.open(this.href);return false;";
		YUIDom.get("itemdetail_image_anchor").href = this.item.link;
	}

	// User 
	document.getElementById("lightboxboxedby").innerHTML = this.item.box_username;
	// Date 
	var dateBoxed = document.getElementById("lightboxdateboxed");
	var dt = new Date(1000 * this.item.date_added);
	dateBoxed.innerHTML = dt.toLocaleString();

	var public_url_input = YUIDom.get("lb_item_public_link");
	if( public_url_input )
	{
		public_url_input.value = "http://"+window["sb_host"]+"/public/item/?id="+this.item.item_id+"&ac="+this.item.public_access_code;
	}

	// Print 
	document.getElementById("lightboxprint").href = "/print/box?id="+this.item.item_id+'&ac='+this.item.public_access_code;
	// Save 
	document.getElementById("lightboxsave").href = "/item/save/?id="+this.item.item_id+'&ac='+this.item.public_access_code;

	// clean up comments box
	var comdiv = document.getElementById ( "lightbox_comments_area" );
	if ( comdiv.hasChildNodes()){
		while (comdiv.firstChild){
   			comdiv.removeChild(comdiv.firstChild);
 		}
	}

	var loadingdlg = YUIDom.get("sb_loading_replies").cloneNode(true);
	loadingdlg.id = "lb_comment_loading";
	comdiv.appendChild( loadingdlg );

	this.getComments();

	/* title */
	var title = this.item.title;
	showTitle(title);

	if( this.from == 0 )
	{
		var url = "/item/getnextandprev/?id="+this.item.item_id;
		var cb = { success:onGetNextAndPreviousCallback, arguments:{ lb:this } };
		YUIRequest.asyncRequest( "GET", url, cb );
	}

	if( SButil.StateManager.is_public )
	{
		/*
		var arr = YUIDom.getElementsByClassName("lightbox_comment_captcha_block", "td", this.htmlObj, addCaptcha );
		this.captchaBlock = arr[0];
		this.captcha_uid = arr[0].captcha_uid;
		*/
	}

	if( SButil.StateManager.log_visits)
	{
		YUIRequest.asyncRequest("GET","/public/logitemvisit/?id="+this.item.id, null, null );
	}

	this.show();

	var arr9 = YUIDom.getElementsByClassName( "prompt", "div", this.htmlObj );
	if(arr9[0]) {
		this.textAreaLabel = arr9[0];
		YUIEvent.addListener( this.textAreaLabel, "click", this.showTextArea, this, true );
		
	}

	SButil.EventManager.addListener("ItemCommentDeleted", onCommentDeleted, this);

	var tagwrapper = YUIDom.getElementsByClassName( "tag_wrapper", "div", this.htmlObj );
	if( tagwrapper[0] )
	{
		while( tagwrapper[0].childNodes.length )
		{
			tagwrapper[0].removeChild(tagwrapper[0].firstChild);		
		}

		var tagSet = this.item.tags;

		for( var t = 0; t < tagSet.length; t++ )
		{
			if( tagSet[t].length )
			{
				var tagdiv = document.createElement("div");
				tagdiv.className = "tag";
				tagdiv.innerHTML = tagSet[t];
				tagwrapper[0].appendChild(tagdiv);
			}
		}
	}

	var tagedit = YUIDom.getElementsByClassName( "tag_edit", "div", this.htmlObj );
	if( tagedit[0] )
	{
		YUIEvent.addListener(tagedit[0],"click", this.showTagEdit, this, true );		
	}

};

LightBoxDialog.prototype.returnToBox =  function()
{
	this.destroy();
};

function addCaptcha( el )
{
	var imp = null;
	if( imp = YUIDom.get("captcha_image_block_imp") )
	{
		imp.parentNode.removeChild( imp );
		imp = null;
	}

	var baseBlock = YUIDom.get("captcha_image_block");

	var children = YUIDom.getChildren( el );	
	for( elm in children ) { el.removeChild( children[elm] ); }

	var block = baseBlock.cloneNode(true);

	block.id="captcha_image_block_imp";

	el.style.display="block"; 

	YUIDom.getElementsByClassName("lightbox_comment_captcha_img", "img", block, 
		function(elm) { elm.src="/extras/captcha/?uid=0"});

	YUIDom.getElementsByClassName("lightbox_comment_captcha", "input", block, 
		function(elm) { elm.id="captcha_0"; });

	el.width = "180";

	el.appendChild( block );
};

LightBoxDialog.prototype.resetConfig =  function( inConfig )
{
	SBui.Stage.sendBeacon();

	YUIEvent.removeListener( "itemdetail_boxnav_prev", "click" );
	YUIEvent.removeListener( "itemdetail_boxnav_next", "click" );

	/*
	if( this.captcha_uid )
		YUIRequest.asyncRequest("GET","/extras/killcaptcha/?uid=0", null, null);
	*/

	if( YUIDom.get("itemdetail_tabview") )
	{
		var textdata_wrapper = YUIDom.get("itemdetail_text_data");
		if( textdata_wrapper )
		{
			textdata_wrapper.innerHTML = this.item.text_data;
		}
	}

	var nextimage = YUIDom.get("itemdetail_next_img");
	var previmage = YUIDom.get("itemdetail_prev_img");

	nextimage.src="http://"+window["sb_static_image_host"]+"/images/circle_load.gif";
	nextimage.width = nextimage.height = 32;
	previmage.src="http://"+window["sb_static_image_host"]+"/images/circle_load.gif";
	previmage.width = previmage.height = 32;

	this.p_config = inConfig;
	var sbitem = new SBCore.Item;
	sbitem.setConfig( inConfig.item );
	this.item = sbitem;

	if( this.item.box_username != window["sb_username"] ) //Hide stuff if item is not owned by current user
	{
		YUIDom.getElementsByClassName("tag_edit","div", this.htmlObj, 
			function(el) { el.style.display="none"; }); 
	}

	//Scale Image for desktop
	var desktopWidth = YUIDom.getClientWidth();
	var desktopHeight = YUIDom.getClientHeight();

	//Scale Image for desktop
	var scaleFactor = 1.0;
	if( (desktopWidth - 400) < this.item.width )
	{
		scaleFactor = ((desktopWidth - 400)/this.item.width);	
	}

	if( (desktopHeight - 200) < (this.item.height * scaleFactor) )
	{
		scaleFactor = ((desktopHeight - 200)/this.item.height );
	}

	var imageWidth = (this.item.width * scaleFactor);
	var imageHeight = (this.item.height * scaleFactor);

	var lbaddcommentsblock = YUIDom.get("lightbox_addcomments_block");
	if( lbaddcommentsblock )
		lbaddcommentsblock.style.display = "none";

	// image in box
	var imgObj = document.getElementById("lightboxsmimage");
	var url = this.item.image_url;

	//var textarea = YUIDom.get("lightbox_addcomment_textarea");
	//textarea.value = "";

	if( url.match(/imgfile/) )
	{
		url = url.replace(/\&amp;/g,'&');
		url = "http://"+window["sb_host"]+url;
	}

	imgObj.src = url;
	imgObj.width = imageWidth;
	imgObj.height = imageHeight;

        var locale = window["sb_language"];
        if( locale == "ja" ) locale = "jp";

        this.editlink = "http://www.pixlr.com/editor/?image="+url;
        this.editlink += "&loc=en&target=http://"+window["sb_host"]+"/edit/pixlrcallback";
        this.editlink += "&method=GET&exit=http://"+window["sb_host"]+"&loc="+locale;

	var public_url_input = YUIDom.get("lb_item_public_link");
	if( public_url_input )
	{
		public_url_input.value = "http://"+window["sb_host"]+"/public/item/?id="+this.item.item_id+"&ac="+this.item.public_access_code;
	}

	// full size image 
	//document.getElementById("lightboxfullsize").href = "/show?id="+this.item.item_id;
	// link host 
	var link_host = this.item.link_host;
	YUIDom.getElementsByClassName("lightboxdispurl", "span", this.htmlObj, function(el){ el.innerHTML = link_host } );
	YUIDom.getElementsByClassName("lightboxdispurl_favicon", "img", this.htmlObj, function(el){ el.src = "http://"+link_host+"/favicon.ico"; } );


	// link 
	if( typeof(this.item.link) == "undefined" )
	{
		YUIDom.get("lightbox_visit_url").style.display = "none";
		YUIDom.get("itemdetail_image_anchor").onclick = "";
	}
	else
	{
		YUIDom.get("lightbox_visit_url").style.display = "block";
		YUIDom.get("lightbox_visit_url").href = this.item.link;
		YUIDom.get("itemdetail_image_anchor").onclick = "window.open(this.href);return false;";
		YUIDom.get("itemdetail_image_anchor").href = this.item.link;
	}

	// User 
	document.getElementById("lightboxboxedby").innerHTML = this.item.username;
	// Date 
	var dateBoxed = document.getElementById("lightboxdateboxed");
	var dt = new Date(1000 * this.item.date_added);
	dateBoxed.innerHTML = dt.toLocaleString();

	var visits = this.item.num_visits;
	YUIDom.getElementsByClassName("itemdetail_stat", "span", this.htmlObj, function(el){ el.innerHTML = visits } );


	var num_comments = this.item.comments.length;
	YUIDom.getElementsByClassName("itemdetail_stat_comments", "span", this.htmlObj, function(el){ el.innerHTML = num_comments } );

	// Print 
	document.getElementById("lightboxprint").href = "/print/box?id="+this.item.id+'&ac='+this.item.public_access_code;
	// Save 
	document.getElementById("lightboxsave").href = "/item/save/?id="+this.item.id+'&ac='+this.item.public_access_code;

	// clean up comments box
	var comdiv = document.getElementById ( "lightbox_comments_area" );
	if ( comdiv.hasChildNodes()){
		while (comdiv.firstChild){
   			comdiv.removeChild(comdiv.firstChild);
 		}
	}

	var loadingdlg = YUIDom.get("sb_loading_replies").cloneNode(true);
	loadingdlg.id = "lb_comment_loading";
	comdiv.appendChild( loadingdlg );

	this.getComments();

	/* title */
	var title = this.item.title;
	showTitle(title);

	if( SButil.StateManager.is_public )
	{
		/*
		var arr = YUIDom.getElementsByClassName("lightbox_comment_captcha_block", "td", this.htmlObj, addCaptcha );
		this.captchaBlock = arr[0];
		this.captcha_uid = arr[0].captcha_uid;
		*/
	}

	if( SButil.StateManager.log_visits)
	{
		YUIRequest.asyncRequest("GET","/public/logitemvisit/?id="+this.item.id, null, null );
	}

	var url = "/item/getnextandprev/?id="+this.item.id;
	var cb = { success:onGetNextAndPreviousCallback, arguments:{ lb:this } };
	YUIRequest.asyncRequest( "GET", url, cb );

	var tagwrapper = YUIDom.getElementsByClassName( "tag_wrapper", "div", this.htmlObj );
	if( tagwrapper[0] )
	{
		while( tagwrapper[0].childNodes.length )
		{
			tagwrapper[0].removeChild(tagwrapper[0].firstChild);		
		}

		var tagSet = this.item.tags;

		for( var t = 0; t < tagSet.length; t++ )
		{
			if( tagSet[t].length )
			{
				var tagdiv = document.createElement("div");
				tagdiv.className = "tag";
				tagdiv.innerHTML = tagSet[t];
				tagwrapper[0].appendChild(tagdiv);
			}
		}
	}

	var tagedit = YUIDom.getElementsByClassName( "tag_edit", "div", this.htmlObj );
	if( tagedit[0] )
	{
		YUIEvent.addListener(tagedit[0],"click", this.showTagEdit, this, true );		
	}
};

LightBoxDialog.prototype.showTagEdit = function(inEvent)
{

	var wrapper = YUIDom.getElementsByClassName( "tag_wrapper", "div", this.htmlObj );
	if( wrapper[0] )
	{
		while( wrapper[0].childNodes.length )
		{
			wrapper[0].removeChild(wrapper[0].firstChild);		
		}

		var taglist = this.item.tags.join(",");

		var edittagsbl = YUIDom.get("edit_tags_block").cloneNode(true);
		this.edittagsblock = edittagsbl;
		var inpdiv = YUIDom.getElementsByClassName( "tagsinput", "input", edittagsbl )[0]; 
		inpdiv.value = taglist;

		var savelink = YUIDom.getElementsByClassName( "savetags", "div", edittagsbl )[0]; 

		var cancellink = YUIDom.getElementsByClassName( "canceledittags", "div", edittagsbl )[0]; 

		wrapper[0].appendChild(edittagsbl);
		YUIEvent.addListener(cancellink,"click",this.closeTagEdit, this, true );
		YUIEvent.addListener(savelink,"click",this.setTags, this, true );

	}


	var editlink = YUIDom.getElementsByClassName( "tag_edit", "div", this.htmlObj );
	if( editlink[0] )
	{
		editlink[0].style.visibility = "hidden";
	}

};

LightBoxDialog.prototype.setTags = function(inEvent)
{
	if( !this.edittagsblock ) return;

	var taglistinput = YUIDom.getElementsByClassName( "tagsinput", "input", this.edittagsblock )[0]; 

	if( taglistinput )
	{
		var tagSet = taglistinput.value.split(",");

		var tagwrapper = YUIDom.getElementsByClassName( "tag_wrapper", "div", this.htmlObj );

		var tagFlat = "";

		this.item.tags = [];

		if( tagwrapper[0] )
		{
			for( var t = 0; t < tagSet.length; t++ )
			{
				if( tagSet[t].length )
				{

				var tagdiv = document.createElement("div");
				tagdiv.className = "tag";
				tagdiv.innerHTML = tagSet[t];
				tagwrapper[0].appendChild(tagdiv);

				this.item.tags.push( tagSet[t] );

				tagFlat += encodeURIComponent(tagSet[t]);
				if( (t+1) < tagSet.length )
					tagFlat += ",";
				}
			}
		}

		//Send the new tags
		var req = "/item/updatetags";
		var pd = "id="+this.item.item_id+"&tags="+tagFlat;

		YUIRequest.asyncRequest( "POST", req, null, pd );

		var obj = { item_id: this.item.item_id, tags: this.item.tags };
		SButil.EventManager.fireEvent( "TagsUpdated", obj );
	}

	var savelink = YUIDom.getElementsByClassName( "savetags", "div", this.edittagsblock)[0]; 
	var cancellink = YUIDom.getElementsByClassName( "canceledittags", "div", this.edittagsblock )[0]; 

	YUIEvent.removeListener(cancellink,"click");
	YUIEvent.removeListener(savelink,"click");


	this.edittagsblock.parentNode.removeChild(this.edittagsblock);
	this.edittagsblock = null;

	var editlink = YUIDom.getElementsByClassName( "tag_edit", "div", this.htmlObj );
	if( editlink[0] )
	{
		editlink[0].style.visibility = "visible";
	}
};

LightBoxDialog.prototype.closeTagEdit = function(inEvent)
{
	if( !this.edittagsblock ) return;

	var tagwrapper = YUIDom.getElementsByClassName( "tag_wrapper", "div", this.htmlObj );
	if( tagwrapper[0] )
	{
		var tagSet = this.item.tags;

		for( var t = 0; t < tagSet.length; t++ )
		{
			var tagdiv = document.createElement("div");
			tagdiv.className = "tag";
			tagdiv.innerHTML = tagSet[t];
			tagwrapper[0].appendChild(tagdiv);
		}
	}

	var savelink = YUIDom.getElementsByClassName( "savetags", "div", this.edittagsblock)[0]; 
	var cancellink = YUIDom.getElementsByClassName( "canceledittags", "div", this.edittagsblock )[0]; 

	YUIEvent.removeListener(cancellink,"click");
	YUIEvent.removeListener(savelink,"click");



	this.edittagsblock.parentNode.removeChild(this.edittagsblock);
	this.edittagsblock = null;

	var editlink = YUIDom.getElementsByClassName( "tag_edit", "div", this.htmlObj );
	if( editlink[0] )
	{
		editlink[0].style.visibility = "visible";
	}
};

function configureAddThis( inEvent, inObj)
{
	return addthis_open(this, '', 'http://'+window["sb_host"]+'/public/item/?id='+inObj.item.id+'&ac='+inObj.item.public_access_code, 'SimplyBox Item: '+inObj.item.title);
}

LightBoxDialog.prototype.resize = function( inEvent )
{
	//Scale Image for desktop
	var desktopWidth = YUIDom.getClientWidth();
	var desktopHeight = YUIDom.getClientHeight();

	//Scale Image for desktop
	var scaleFactor = 1.0;
	if( (desktopWidth - 410) < this.item.width )
	{
		scaleFactor = ((desktopWidth - 410)/this.item.width);	
	}

	if( (desktopHeight - 200) < (this.item.height * scaleFactor) )
	{
		scaleFactor = ((desktopHeight - 200)/this.item.height );
	}

	var imageWidth = (this.item.width * scaleFactor);
	var imageHeight = (this.item.height * scaleFactor);

	// image in box
	var imgObj = document.getElementById("lightboxsmimage");
	imgObj.width = imageWidth;
	imgObj.height = imageHeight;
};

LightBoxDialog.prototype.confirmDeleteItem = function( inEvent )
{
	//document.getElementById("deleteboxdiv").style.display = 'block';
}

LightBoxDialog.prototype.cancelDeleteItem = function( inEvent )
{
	//document.getElementById("deleteboxdiv").style.display = 'none';
}

/*
	Removes the Item (locally and on the server)	
*/
LightBoxDialog.prototype.deleteItem = function() 
{
	var req = "/item/delete/?iid="+this.item.item_id;
	YUIRequest.asyncRequest( "GET", req, 
			{ success:deleteItemSuccess, 
			  failure:deleteItemFailure,
		  	arguments:{ item:this } } );
};

function deleteItemSuccess( inObj )
{
	if( inObj.responseText == "1" )
	{
		var lbDlg = this.arguments.item;
		lbDlg.item.kill();
		lbDlg.destroy();
		SButil.EventManager.fireEvent( "ItemDeleted", lbDlg.item );
	}
}

function deleteItemFailure( inObj ) 
{
	alert("deleteItemFailure");
}

function onGetNextAndPreviousCallback( inReq )
{
	var results = YUIJSON.parse( inReq.responseText );

	var lb = this.arguments.lb;

	var nextImg = YUIDom.get("itemdetail_next_img");
	var prevImg = YUIDom.get("itemdetail_prev_img");

	YUIEvent.removeListener( "itemdetail_boxnav_prev", "click" );
	YUIEvent.removeListener( "itemdetail_boxnav_next", "click" );

	if( results.prev && results.prev.id && prevImg )
	{	
		var boxnavhtml = YUIDom.get( "itemdetail_boxnav_prev" );
		if( boxnavhtml )
			boxnavhtml.style.visibility = "visible";

		previtem = results.prev;

		//Scale Image for desktop
		var scaleFactor = 1.0;
		if( 100  < previtem.width ) { scaleFactor = ((100)/previtem.width);}
		if( 100 < (previtem.height * scaleFactor) ) { scaleFactor = ((100)/previtem.height); }

		prevImg.src = "about:blank";
		prevImg.width  = (previtem.width * scaleFactor);
		prevImg.height = (previtem.height * scaleFactor);
		var url = previtem.image_url;

		if( url.match(/imgfile/) )
		{
			url = url.replace(/\&amp;/g,'&');
			url = "http://"+window["sb_host"]+url;
		}
		prevImg.src = url;

		YUIEvent.addListener( "itemdetail_boxnav_prev", "click", onBoxNav, { item:previtem }, lb);
	}
	else
	{
		var boxnavhtml = YUIDom.get( "itemdetail_boxnav_prev" );
		if( boxnavhtml )
			boxnavhtml.style.visibility = "hidden";

		if( prevImg )
			prevImg.src = "about:blank";
	}

	if( results.next && results.next.id && nextImg )
	{	
		nextitem = results.next;

		//Scale Image for desktop
		var scaleFactor = 1.0;
		if( 100  < nextitem.width ) { scaleFactor = ((100)/nextitem.width);}
		if( 100 < (nextitem.height * scaleFactor) ) { scaleFactor = ((100)/nextitem.height); }

		nextImg.src = "about:blank";
		nextImg.width  = (nextitem.width * scaleFactor);
		nextImg.height = (nextitem.height * scaleFactor);
		var url = nextitem.image_url;

		if( url.match(/imgfile/) )
		{
			url = url.replace(/\&amp;/g,'&');
			url = "http://"+window["sb_host"]+url;
		}
		nextImg.src = url;

		YUIDom.get( "itemdetail_boxnav_next" ).style.visibility = "visible";
		YUIEvent.addListener( "itemdetail_boxnav_next", "click", onBoxNav, {item:nextitem }, lb);
	}
	else
	{
		var boxnavhtml = YUIDom.get( "itemdetail_boxnav_next" );
		if( boxnavhtml )
			boxnavhtml.style.visibility = "hidden";

		if( nextImg )
			nextImg.src = "about:blank";
	}
}

LightBoxDialog.prototype.getComments = function()
{
	var sURL = "/comment/getbyitem"
	var pd = "item_id="+this.item.id+"&level=0";	
	
	var cb = { success:this.getCommentsSuccess, arguments:{ item:this.item, srcobj:this } };
	YUIRequest.asyncRequest( "POST", sURL, cb, pd );
};

LightBoxDialog.prototype.getCommentsSuccess = function(obj)
{
	var commentsJSON = YAHOO.lang.JSON.parse(obj.responseText);

	var no_comments = true;

	this.arguments.item.comments = [];

	var commentsArea = YUIDom.get("lightbox_comments_area");
	var loadingdlg = YUIDom.get("lb_comment_loading");
	if( loadingdlg ) 
	{
		loadingdlg.parentNode.removeChild( loadingdlg );
	}

	for( c in commentsJSON.comments )
	{
		var comment = new SBCore.Comment;
		comment.setConfig( commentsJSON.comments[c] );
		this.arguments.item.comments.push(comment);
		comment.item = this.arguments.item;

		var branchObj = new SBui.LightBoxCommentView;
		branchObj.setConfig( { comment_obj:comment } );
		commentsArea.appendChild( branchObj.htmlObj  );

		no_comments = false;
	}

	var lbaddcommentsblock = YUIDom.get("lightbox_addcomments_block");
	if( lbaddcommentsblock )
		lbaddcommentsblock.style.display = "block";


	if( no_comments )
	{
		var el = YUIDom.get("listview_emptycomment");
		var newel = el.cloneNode(true);
		YUIDom.setStyle( newel,"margin","5px 0px 10px 20px" );
		YUIDom.setStyle( newel,"max-width","none");
		newel.id = "lightbox_emptycomment_"+this.arguments.item.id;
		commentsArea.appendChild(newel);
	}
	else
	{
		var num_comments = commentsJSON.comments.length;
		YUIDom.getElementsByClassName("itemdetail_stat_comments", "span", this.arguments.srcobj.htmlObj, function(el){ el.innerHTML = num_comments } );
	}
};

LightBoxDialog.prototype.hideTextArea = function( ev )
{
	var comblock = YUIDom.get("comment_entry");

	YUIDom.getElementsByClassName( "cancelcomment", "div", comblock, 
		function(el) { YUIEvent.removeListener( el, "click" ); });

	YUIDom.getElementsByClassName( "postcomment", "div", comblock, 
		function(el) { YUIEvent.removeListener( el, "click" ); });

	if( comblock )
	{
		comblock.parentNode.removeChild( comblock );
		comblock = null;
	}

	YUIDom.getElementsByClassName( "prompt", "div", this.htmlObj , function(el) { el.style.display="block"; } );

	if( ev ) YUIEvent.stopEvent( ev );
};

LightBoxDialog.prototype.showTextArea = function( ev )
{
	var oldcom = YUIDom.get("comment_entry");
	if( oldcom ) { oldcom.closer(); }

	var comblock = YUIDom.get("newcomment_block").cloneNode(true);
	comblock.id = "comment_entry";
	comblock.className = "addcommentblock";

	/*
	if( window["sb_is_signed_in"] == "0" )
		YUIDom.getElementsByClassName( "captcha_loc", "td", comblock, function(el) { addCaptcha(el); } );
	*/

	YUIDom.getElementsByClassName( "prompt", "div", this.htmlObj , function(el) { el.style.display="none"; } );
	YUIDom.getElementsByClassName( "edit", "div", this.htmlObj , function(el) { el.appendChild( comblock ); } );
	YUIDom.getElementsByClassName( "commenttextarea", "textarea", comblock , function(el) { el.focus(); } );

	comblock.closer = this.hideTextArea;

	var viewobj = this;
	YUIDom.getElementsByClassName( "cancelcomment", "div", comblock, 
		function(el) { YUIEvent.addListener( el, "click", viewobj.hideTextArea, viewobj, true ); });

	YUIDom.getElementsByClassName( "postcomment", "div", comblock, 
		function(el) { YUIEvent.addListener( el, "click", viewobj.addComment, viewobj, true ); });

	YUIEvent.stopEvent( ev );
};

LightBoxDialog.prototype.addComment = function( ev )
{
	var comblock = YUIDom.get("comment_entry");
	var textarea = YUIDom.getElementsByClassName( "commenttextarea", "textarea", comblock )[0];

	var ncomment = new SBCore.Comment;
	var d = new Date();
	ncomment.setConfig( { 	"user":window["sb_username"], 
				"date_added":(d.getTime() / 1000), 
				"text":textarea.value,
				"color":window["sb_bubble_color"]
			    } );

	if( window["sb_is_signed_in"] == "0" )
	{
		var captcha_block = YUIDom.get("captcha_0");	
		if( captcha_block )
		{
			ncomment.captcha_value = captcha_block.value;
		}
	}

	this.hideTextArea(null);	

	//Is this the first comment?  Then kill the empty comment block
	if( !this.item.comments.length )
	{
		var emptycommentblock = YUIDom.get("lightbox_emptycomment_"+this.item.item_id);
		if( emptycommentblock )
		{
			emptycommentblock.style.display = "none";
			emptycommentblock.parentNode.removeChild(emptycommentblock);
		}
	}

	this.item.addComment( ncomment );

	SButil.EventManager.fireEvent( "ItemCommentAdded", { id:this.item.item_id } );

	var commentsArea = YUIDom.get("lightbox_comments_area");

	var branchObj = new SBui.LightBoxCommentView;
	branchObj.setConfig( { comment_obj:ncomment, noreply:true } );
	YUIDom.setStyle( branchObj.htmlObj, "opacity", 0 );
	commentsArea.appendChild( branchObj.htmlObj );

	var attributes = { opacity:{ to:1 } };	
	var anim = new YUIAnim( branchObj.htmlObj, attributes, 0.3, YUIEasing.easeIn);
	anim.animate();

	var num_comments = this.item.comments.length;
	YUIDom.getElementsByClassName("itemdetail_stat_comments", "span", this.htmlObj, function(el){ el.innerHTML = num_comments } );

	if( ev ) YUIEvent.stopEvent( ev );
};



function onBoxNav( inEvent, inObj )
{
	this.resetConfig( inObj );
}

/*
 	Function: getConfig
 	Returns a configuration array for the LightBoxDialog.
 
 	See <setConfig> for configuration array definition
 */
LightBoxDialog.prototype.getConfig = function()
{
	return this.p_config;
};

/*
 	Function: show 
 	Displays the LightBoxDialog (and begins modal session)	
 */
LightBoxDialog.prototype.show = function()
{	
	if( this.overlayObj && this.overlayObj.style.display == "none" )
	{
		this.parentNode = this.htmlObj.parentNode;
		this.overlayObj.appendChild( this.htmlObj );
		this.overlayObj.style.display = "block";
	}
};

/*
 	Function: hide 
 	Removes the LightBoxDialog (and ends modal session)	
 */
LightBoxDialog.prototype.hide = function()
{
	if( this.overlayObj && this.overlayObj.style.display == "block" )
	{
		YUIEvent.removeListener( "itemdetail_boxnav_prev", "click" );
		YUIEvent.removeListener( "itemdetail_boxnav_next", "click" );

		cancelTitleEdit();
		this.overlayObj.style.display = "none";

		YUIEvent.removeListener( window, "resize" );

		this.parentNode.appendChild( this.htmlObj );

		/*
		if( this.captcha_uid )
		YUIRequest.asyncRequest("GET","/extras/killcaptcha/?uid=0", null, null);
		*/
	}
};

/*
 	Function: destroy 
 	Removes the LightBoxDialog, cleans up memory	
 */
LightBoxDialog.prototype.destroy = function( inEvent )
{
	this.hide();
	this.cancelDeleteItem();


	SButil.EventManager.removeListener("ItemCommentDeleted", onCommentDeleted, this);
};


/*
 	Function: isShowing 
 	Returns whether the LightBoxDialog is currently displayed	
 */
LightBoxDialog.prototype.isShowing = function()
{
	return this.p_isShowing;
};


//Group: Delegate Methods 
/*
 	Function: validate
 	A stub function which is called before submission of the LightBoxDialog.
 	Returns TRUE to always allow form submission
 */
LightBoxDialog.prototype.validate = function()
{
	return true;
};

/*
 	Function: callbackSuccess 
 	A stub function which is called in a Form dialog if the submission succeeded.
 
 	inReq - the request object 
 */
LightBoxDialog.prototype.callbackSuccess = function( inReq )
{
	this.arguments.dlgObj.destroy();	
};

/*
 	Function: callbackFailure
 	A stub function which is called in a Form dialog if the submission failed.
 
 	inReq - the request object 
 */
LightBoxDialog.prototype.callbackFailure = function( inReq )
{
	//YAHOO.log("FAILED CALLBACK!");
};

LightBoxDialog.prototype.editImage = function( inEvent )
{
	Set_Cookie( "sbedit", this.item.id );
	var winwidth = YUIDom.getViewportWidth();
	var winheight = YUIDom.getViewportHeight();

	var browidth = YUIDom.getClientWidth();
	var broheight= YUIDom.getClientHeight();

	if( browidth <= 250 || broheight <= 250 ) return;

	this.editwindow = window.open(this.editlink,'mywin','left='+((winwidth/2) - ((browidth/2) - 50))+',top='+((winheight/2) - ((broheight/2)-50))+',width='+(browidth-100)+',height='+(broheight-100)+',toolbar=no,resizable=yes,location=no,status=no,menubar=no');
	
	this.editwindowtimer = setInterval( this.onEditWindowTimer, 500 );
	
	return;
	var editlayer = YUIDom.get("itemdetail_editlayer");
	if( editlayer )
	{
		editlayer.style.display = "block";
		var editframe = YUIDom.get("itemdetail_edit_iframe");	
		editframe.src = this.editlink;
	}
};

LightBoxDialog.prototype.onEditWindowTimer = function()
{
	var editwindow = SBui.LightBoxDialog.editwindow;
	var editwindowtimer = SBui.LightBoxDialog.editwindowtimer;

	if( editwindow.closed )
	{
		clearInterval( editwindowtimer );
		editWindowClosed(); 
	}
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function editWindowClosed( ev )
{
	var lb = SBui.LightBoxDialog;
	var url = "/item/getbyid/?id="+lb.item.id;
	var cb = { success:onReloadLightBox, arguments:{ lb:lb} };
	YUIRequest.asyncRequest( "GET", url, cb );
}

function onReloadLightBox( inReq )
{
	var results = YUIJSON.parse( inReq.responseText );

	var lb = this.arguments.lb;


	if( results ) 
	{
		lb.item.resetConfig( results );
		lb.resetConfig( { item:lb.item } );	
	}
}

function destruct( inObj ) { delete inObj; }


/* ------- Title manipulation ------- */
	
function titleEdit()
{
	document.getElementById("sb_lightbox_title_input").value = this.item.title;
	document.getElementById("sb_lightbox_title_editor").style.display = "block";
	document.getElementById("lightboxtitle_wrapper").style.display = "none";
	var titleBoxWidth = document.getElementById('sb_dialog_titlemid').offsetWidth;
	var titleEditWidth = Math.round(titleBoxWidth*0.7);
	document.getElementById("sb_lightbox_title_input").style.width = titleEditWidth+"px";
}

function cancelTitleEdit()
{
	document.getElementById("sb_lightbox_title_editor").style.display = "none";
	document.getElementById("lightboxtitle_wrapper").style.display = "block";
	document.getElementById("sb_lightbox_title_input").value = "";
	document.getElementById("sb_lightbox_title_input").style.backgroundColor = "#FFFFFF";
}

LightBoxDialog.prototype.saveTitleCallback = function(obj)
{
	var resp = YAHOO.lang.JSON.parse(obj.responseText);
	var lightboxname = document.getElementById('lightboxboxname');

	if( resp != "0" )
	{
		this.arguments.obj.item.title = resp;
		showTitle(resp);
	}

	cancelTitleEdit();
}

function saveTitleEdit(e)
{
	var inputElm = document.getElementById("sb_lightbox_title_input");
	var sUrl = "/item/updatetitle/?bid="+this.item.item_id+"&title="+encodeURIComponent(inputElm.value);
	YUIRequest.asyncRequest( "GET", sUrl, { success:this.saveTitleCallback, arguments:{ obj:this } } );
	inputElm.style.backgroundColor ="#FFEEAA";
	inputElm.value=SBtranslation[31];

}

function showTitle(str)
{
	document.getElementById("lightboxboxname").innerHTML = "";
	if(!str) {
		return;
	}
	var boxWidth = document.getElementById("sb_dialog_titlemid").offsetWidth;
	var shortCut = Math.round(boxWidth*0.35); 
	var title = str;
	var trancTitle = title.trunc("sb_dialog_titlemid", false, shortCut);
	document.getElementById("lightboxboxname").innerHTML = trancTitle;		
}

/* ------- add comments ------- */ 
	
function addComment( inEvent )
{
	var textarea = YUIDom.get("lightbox_addcomment_textarea");
	var comment = textarea.value;

	if(!comment) { return; }

	/*
	var sbcaptcha = "";
	var captcha_uid = "";

	if( this.captcha_uid )
	{
		var captcha = YUIDom.get("captcha_"+this.captcha_uid);
		if( captcha ) sbcaptcha = captcha.value;

		captcha_uid = this.captcha_uid;
	}
	*/

	var sURL = "/comment/add/"
	var pd = "item_id="+this.item.id+"&comment="+encodeURIComponent(comment);
	//pd += "&sbcaptcha="+sbcaptcha+"&captcha_uid="+captcha_uid;

	var cb = { success:saveCommentSuccess, arguments:{ lb:this} };
	YUIRequest.asyncRequest( "POST", sURL, cb, pd );
		
	textarea.style.backgroundColor ="#FFEEAA";
	textarea.value=SBtranslation[30];
}

function saveCommentSuccess( inReq )
{
	var lb = this.arguments.lb;

	if( SButil.StateManager.is_public )
	{
		//addCaptcha( lb.captchaBlock );
		//lb.captcha_uid = lb.captchaBlock.captcha_uid;
	}

	SButil.EventManager.fireEvent( "ItemCommentAdded", { id:this.arguments.lb.item.id } );

	var textarea = YUIDom.get("lightbox_addcomment_textarea");
	textarea.style.backgroundColor ="#FFF";
	textarea.value = "";
	this.arguments.lb.itemComments.getComments();
}

function onCommentDeleted( inEvent, inArgs )
{
	if( inArgs[0].item_id == this.item.id )
	{	
		var num_comments = this.item.comments.length;
	YUIDom.getElementsByClassName("itemdetail_stat_comments", "span", this.htmlObj, function(el){ el.innerHTML = num_comments } );
	}
}

function commentboxTextChanged(e, obj)
{
	document.getElementById("sb_comment_word_count").value = 
					1000 - document.getElementById("commentbox").value.length;
}

window['SB']['ui']['LightBoxDialog'] = new LightBoxDialog();

})();
