/*
Plugin Name: CommentPress
Plugin URI: http://www.commentpress.cc
Description:  CommentPress allows readers to comment paragraph by paragraph in the margins of a text. You can use it to annotate, gloss, workshop, debate and more!
Author: Eddie Tejeda
Version: 2.3
Author URI: http://www.visudo.com
License: GPLv2 (http://creativecommons.org/licenses/GPL/2.0/)



The functions: containerResize, buildContainers, setIcon , setButtons, minimize and iconize where developed by Matteo Bicocchi on JQuery
© 2002-2008 Open Lab srl, Matteo Bicocchi
www.open-lab.com - info@open-lab.com
version 1.0
GPL (GPL-LICENSE.txt) licenses.
*/

var msie=$.browser.msie;
var msie6=$.browser.msie && $.browser.version=="6.0";
var safari=$.browser.safari;
var mozilla=$.browser.mozilla;
var zi=10000;
var on_load_selected_paragraph;

// CHANGE MATT TO TRACK CURRENTLY SELECTED COMMENT BLOCK
var current_block;


jQuery(document).ready(function(){

	/************************************************/
	//
	//               DOM Manipulation
	//  
	/************************************************/


	//recreate comment section
	jQuery("body").append('<div id="accordion"></div>');

	jQuery.cookie('text_selection', null);
	
	
	
	//the wholepage group
	var whole_page_count = 0;
	var comment_ids = new Array();	
	for ( var j in commment_text_signature )
	{
		if(commment_text_signature[j] == '')
		{
			comment_ids[whole_page_count] = '#comment-' + j;			
			whole_page_count++;
		}		
	}	
	
	// CHANGE MATT TO REMOVE LINK FOR WHOLE PAGE
	//jQuery("#accordion").append('<div name="comment-block-0"  id="comment-block-0"><h6 class="commentarea"><a  id="comment-" href="#0">Whole Page ('+whole_page_count+')</a></h6><div><ol class="subcommentlist" id="comment-group-"></ol></div></div>');		
	jQuery("#accordion").append('<div name="comment-block-0"  id="comment-block-0"><h6 class="commentarea">Comments for Entire Chapter ('+whole_page_count+')</h6><div><ol class="subcommentlist" id="comment-group-"></ol>All comments are moderated.</div></div>');


	
	for( var k in comment_ids)
	{
		jQuery('#comment-group-').append( jQuery(comment_ids[k]) );			
	}
	jQuery('#comment-group-').append( jQuery('#respond').html() );

	//this is not the most efficient way to do this, but it works alright. we go through each paragraph and see which
	//of the comment signatures, found in commment_text_signature, matches and we put that comment in the right place.
	jQuery('.commenticon').each( function (i) {
		
		var comments = new Array();
		var comment_ids = new Array();
		var count = 0;
		var text_signature = '';
		for ( var j in commment_text_signature )
		{
		
			if( similarString( commment_text_signature[j], jQuery(this).attr('id')) > 0.90 )
			{
				comments[count] = commment_text_signature[j];
				comment_ids[count] = '#comment-' + j;
				count++;
			}
			text_signature = commment_text_signature[j];
		}
		
		
		var paragraph = i + 1;
		// CHANGE MATT TO HIDE UGLY ACCORDION STUFF
		//jQuery("#accordion").append('<div name="comment-block-' + paragraph + '" id="comment-block-' + paragraph + '"><h6><a class="commentarea" id="comment-'+ text_signatures[i] + '" href="#' + paragraph + '">Paragraph '+ paragraph +' (' + count + ')</a></h6><div style="height: 100% !important; padding: 5px !important;"><ol class="subcommentlist" id="comment-group-'+ text_signatures[i] +'"></ol></div></div>');
		jQuery("#accordion").append('<div name="comment-block-' + paragraph + '" id="comment-block-' + paragraph + '" style="display:none;"><h6>Comments for Paragraph '+ paragraph +' (' + count + ')</h6><div style="height: 100% !important; padding: 5px !important;"><ol class="subcommentlist" id="comment-group-'+ text_signatures[i] +'"></ol>All comments are moderated.</div></div>');		
		
		for( var k in comment_ids)
		{
			jQuery('#comment-group-'+ text_signatures[i]).append( jQuery(comment_ids[k]) );			
		}
		
		jQuery('#comment-group-'+ text_signatures[i]).append( jQuery('#respond').html() );

		
	})

	
	//if there is no comment area, things break. lets just create one to be safe
	if(  !jQuery('#comments').length  ) 
	{
		jQuery('body').append("<div id='comments'> </div>");            
	}

	var user_buttons, resizable, draggable;
	if(allow_users_to_iconize){ user_buttons = 'i,'; }
	if(allow_users_to_minimize){ user_buttons += 'm';	}
	if(allow_users_to_resize && (mozilla) ){ resizable = 'resizable'; }
	if(allow_users_to_drag && (!safari) ){ draggable = 'draggable'; }



	//get the existing comment area, and put put it around new html, which will be the floating box
	jQuery('#comments, .commentlist').wrapAll('<div id="commentbox" class="container '+ resizable + ' ' + draggable + ' ' + default_skin+'"  buttons="'+user_buttons+'"><div id="commentwindow"></div></div>');
	jQuery('#respond').appendTo('#commentwindow');
	jQuery('#commentbox').appendTo('body');
	jQuery('#commentbox').html('<table cellpadding="0" cellspacing="0" class="containerTable"><tr class="top"><td class="no"> </td><td class="n"><span id="commentboxtitle"></span></td><td class="ne">&nbsp;</td></tr><tr unselectable="on" class="middle"><td class="o"> </td><td class="c" id="comment_contents"></td><td class="e"> </td></tr><tr class="bottom"><td class="so"> </td><td class="s"></td><td class="se"> </td></tr></table>');
	jQuery('#commentboxtitle').html( jQuery('#comments').html() );
	
	jQuery("#accordion").appendTo("#comment_contents");	
		
	//build the comment area
	jQuery(".container").buildContainers();
	
	
	
	//the position of the commentbox. defined by admin or by user moving it?
	if( allow_users_to_save_position && jQuery.cookie('left_postion_commentbox') && jQuery.cookie('top_postion_commentbox'))
	{
		//cookie defined
		jQuery("#commentbox").css("left", jQuery.cookie('left_postion_commentbox') + 'px');
		jQuery("#commentbox").css("top", jQuery.cookie('top_postion_commentbox') + 'px');
	}
	else
	{
		// sysadmin defined
		jQuery("#commentbox").css("top", default_top_position );
		jQuery("#commentbox").css("left", default_left_position);
	}
	

	//position the commenbox
	var commentbox = jQuery("#commentbox");
	var left = commentbox.position().left;
	var top = commentbox.position().top;
	var width = commentbox.width();      
	var height = commentbox.height();

	jQuery("#commentbox").css('height' , default_height);
	jQuery("#commentbox").css('width', default_width);

	function getParagraphNumberByCommentId(comment_id)
	{
		var text_signature = getTextSignatureByCommentId(comment_id);

		for ( var i in text_signatures )
		{
			if( similarString( text_signatures[i], text_signature) > 0.90 )
			{
				return i+1;
			}
		}
		
	}
	

	
	function getTextSignatureByParagraphNumber(paragraph){
		return text_signatures[paragraph];
	}

	function getTextSignatureByCommentId(comment_id)
	{
		return commment_text_signature[comment_id];
	}

	function getCommentIdByTextSignature(signature)
	{
		return jQuery.inArray(signature, commment_text_signature)
		//return commment_text_signature.indexOf(signature);
	}

	function getParagraphNumberByTextSignature(signature)
	{
		
		return jQuery.inArray(signature, text_signatures)
		//return text_signatures.indexOf(signature);
	}


	//http://www.idealog.us/2006/06/javascript_to_p.html
	function getQueryVariable(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return false;
	}

	/************************************************/
	//
	//               Major Interaction Code 
	//  
	/************************************************/
	
	jQuery(window).mouseup(function(event)  {
		var target = event.target;
		
		var text_selection = getSelection()
		if( text_selection ){			
			if(jQuery(target).attr('class') == 'paragraphtext' ){
				
				jQuery.cookie('text_selection', text_selection, { path: '/', expires: 1});
				highlightSelection();
				var body = document.getElementsByTagName("body")[0];
				getSelection().collapse(body,0);
			}
		}
	});
			
			
	
			
	jQuery(window).mousedown(function(event)  {
		
		var target = event.target;
		
		if(jQuery.cookie('text_selection') != null && allow_text_selection){
			if( jQuery(target).attr('class') == 'paragraphtext' ){
				if( jQuery.cookie('text_selection').length > 0 ){
					unhighlightSelection();
				}
			}
		}
		var $kids = jQuery('.containerTable').children();
		
				
		if(  !$kids.find( jQuery(target).attr('id') ) ||  jQuery(target).attr('id') == 'page' ||  jQuery(target).attr('id') == 'content' ||  jQuery(target).attr('class') == 'paragraphtext'  ){
			unhighlightText();			
		}
		//alert(jQuery(target).name)
		/*
		else if(jQuery(target).attr('class') == '' || jQuery(target).attr('class') == 'content' || jQuery(target).attr('class') == 'paragraphtext' ){
			unhighlightText();						
		}
		*/
	});
	
	
	function contentResize() 
	 {

	 	var text_signature = jQuery.cookie('text_signature');

	 	var paragraph_number = getParagraphNumberByTextSignature(text_signature);
	 	if(paragraph_number >= 0){
	 		//alert(paragraph_number);
	 		var top = jQuery( '.textblock' ).eq(paragraph_number).position().top;
	 		var width = jQuery( '.textblock' ).eq(paragraph_number).width();
	 		var height = jQuery( '.textblock' ).eq(paragraph_number).height();
	 		jQuery( '#selected_block' ).css( {top: top, width: width, height: height} );
	 	}
	 }

	jQuery( window ).wresize( contentResize );
	
	/*
	jQuery('.paragraphtext').mouseup(function(event){

		var text_selection = getSelection()
		if( text_selection ){
			jQuery.cookie('text_selection', text_selection, {path: '/'});
			highlightSelection();
		}

		var body = document.getElementsByTagName("body")[0];
		window.getSelection().collapse(body,0);			
		
	});*/
	
/*		
	jQuery.fn.highlightToggle = function(speed, easing, callback) {
		var width = this.width() + parseInt(this.css('paddingLeft')) + parseInt(this.css('paddingRight'));
		this.animate({marginRight: parseInt(this.css('marginRight')) <0 ? 0 : -width}, speed, easing, callback);
		jQuery.cookie('sidebar', this.css('marginRight'), { path: '/'} );			
		
	};


	jQuery('#togglerbutton').click(function() {
		jQuery('#sidebar').blindToggle('slow');
	});
*/
		
	/** 
	 * @description: clicking on the little comment icon
	 * @todo: 
	 *
	 */
	jQuery(".commenticon").click(function (e) {
		
		var text_signature = getTextSignatureByParagraphNumber(jQuery('.commenticon').index(this));
		selectParagraph(text_signature);
		paragraphnumber  = getParagraphNumberByTextSignature(text_signature);
		if(paragraphnumber >= 0){
			if( jQuery.cookie('selection_paragraph') != paragraphnumber){
				unhighlightSelection();	
			}
		}
		document.location.hash = "#" + (jQuery('.commenticon').index(this) + 1);
	});
	
	function selectParagraph(text_signature){


		
		var paragraphnumber = getParagraphNumberByTextSignature(text_signature);
		
		var textblock = jQuery("#textblock-" + paragraphnumber);
		var commentbox = jQuery("#commentbox");

		var left = textblock.position().left;
		var top = textblock.position().top;

		//alert('left' + left);
		var width = textblock.width();      
		var height = textblock.height();
		var scrollto = (top > 100)  ? (top - 100) : 0;
		
		var textblock_xpath = getElementXPath(this);
		//console.log(textblock_xpath);
		
		jQuery('html, body').scrollTo(scrollto, 800);
		jQuery('.container .containerBody').scrollTo( jQuery('#comment-block-' + paragraphnumber), 800);

		unhighlightText();
		highlightText(top, left, width, height);
		
		jQuery.cookie('text_signature', text_signature, { path: '/', expires: 1} );	
		jQuery.cookie('selection_xpath', textblock_xpath, { path: '/', expires: 1} );	
			
		// CHANGE MATT TO SHOW CONTENT INSTEAD OF ACCORDION
		//alert(paragraphnumber + 1+" "+text_signatures[paragraphnumber]);

		jQuery('#comment-block-0').attr({style : "display: none;"});
		jQuery('#comment-block-'+current_block).attr({style : "display: none;"});

		pPlusOne = paragraphnumber + 1;
		current_block = pPlusOne;

		jQuery('#comment-block-'+pPlusOne).attr({style : "display: inline;"});
		jQuery('#accordion').accordion('activate',  parseInt(pPlusOne) );


	}



    $(".comment").hover(
      function () {
		var selection = '#selection-' + jQuery(this).attr('id').substring(8);
		jQuery(selection).css('text-decoration', 'underline');
      }, 
      function () {
		var selection = '#selection-' + jQuery(this).attr('id').substring(8);
		jQuery(selection).css('text-decoration', 'none');
      }
    );

		
	/** 
	 * @description: clicking on the commentarea paragraph block
	 * @todo: 
	 *
	 */
	jQuery(".commentarea").click(function (e) {

		var paragraphnumber = 0;
		unhighlightText();		
		
		if( jQuery(this).attr('class') == 'selected')
		{

		}
		else if( jQuery('.commentarea').index(this) == 0)
		{
			//selecting "whole page" 
			// CHANGE BY MATT TO MAKE PAGE SCOLL TO 0 NOT 75
			jQuery('html, body').scrollTo(0, 1000);			
			
		}
		else
		{
			var text_signature = jQuery(this).attr('id').substring(8);

			paragraphnumber = getParagraphNumberByTextSignature(text_signature);
			var textblock = jQuery("#textblock-" + paragraphnumber);
			var left = textblock.position().left;
			var top = textblock.position().top;
			var width = textblock.width();      
			var height = textblock.height();			
			var top_header = default_top_position.split('px');

			var selection_paragraph = jQuery.cookie('selection_paragraph');
			if((selection_paragraph) == jQuery('.commentarea').index(this) -1 )
			{
			}
			else
			{
				//alert(selection_paragraph);
				//alert(jQuery('.commentarea').index(this) -1);
				
				unhighlightSelection();				
			}

			scrollto = (top - top_header[0]);
			jQuery('html, body').scrollTo( scrollto, 1000);
			
			unhighlightText();
			highlightText(top, left, width, height);			
			jQuery.cookie('text_signature', text_signatures[ ( jQuery('.commentarea').index(this) - 1) ], { path: '/', expires: 1} );	
		}
		
		//scroll the comment area
		jQuery('.container .containerBody').scrollTo( 0, 0);
		jQuery('.container .containerBody').scrollTo( jQuery('#comment-block-' + (paragraphnumber)), 800);
		document.location.hash = "#" +(paragraphnumber +1) ;
		

	});



	/************************************************/
	//
	//               Minor Interaction Code 
	//  
	/************************************************/

	
	jQuery("#accordion").accordion({
		header: "h6",
		alwaysOpen: false,
		animated: false
	});

	// CHANGE MATT TO ALLOW WHOLE PAGE COMMENTS TO OPEN ON LOAD
	//jQuery('#accordion').accordion('activate', false);
	//jQuery("#respond h3").empty();
	jQuery("textarea").attr('rows', 5);
	
	
	if(allow_users_to_resize)
	{
		jQuery(".containerTable").resizable({
			transparent: true,
			handles: "all",
			stop: function (e) { resizing(e); }
		});	
	}
		
	//we need to do this to have fixed window. or else things get weird!
	function resizing(e)
	{

		var height = jQuery('.containerTable').css('height');
		var width = jQuery('.containerTable').css('width');
		
		jQuery('#commentbox').css('height', height);
		jQuery('#commentbox').css('width', width);
	}
	

	jQuery('#commentwindow').mousewheel(function(event, delta) {
		return false; // prevent default
	});


	jQuery('input, textarea').click(function (e) {
		jQuery(this).focus();
	});
		



	/** 
	 * @description: highlight the current text
	 * @todo: implement this function using the jquery extend/fn plugin system. make all objects highliteable
	 *
	 */	
	function highlightText(top, left, width, height) 
	{
		var highlite = jQuery.create('div', 
						{'id':'selected_block', 
						'class':'selected_block',
						'style':'top: '+(top)+'px; left: '+(left)+'px; width: ' +width+'px; height: '+ (height) +'px;' 
						}, '');

		jQuery('#content').append(highlite);	
	}
	
	
	function highlightSelection()
	{
		if(allow_text_selection)
		{
		
			var selection = getSelection();
			var range;
		
			if(range = getRangeObject(selection))
			{
				var node = range.commonAncestorContainer;

						
				if(node)
				{
					var html = new XMLSerializer().serializeToString(node);
					var endnode = null;
					var endoffset = null;
					var selectionlength = selection.toString.length;
					
					if(selection.anchorOffset < selection.focusOffset)
					{
					
						if(selection.anchorNode == selection.focusNode){
							endnode = selection.focusNode;
							endoffset = selection.focusOffset;
						}
						else
						{
							endnode = selection.anchorNode;						
							endoffset = selection.anchorNode.textContent.length;	
						}
					
						range.setStart(selection.anchorNode,selection.anchorOffset);
						range.setEnd(endnode, endoffset);
					
						// this should be below else , but now we are going to ignore 
						// backwards selection					
						var newNode = document.createElement("span");
						newNode.id = 'selected_text';

						range.surroundContents(newNode);

						var selection_paragraph = jQuery(node.parentNode.parentNode).attr('id').substring(10);
						jQuery.cookie('selection_paragraph', selection_paragraph, { path: '/', expires: 1} );
					
					}
					else
					{
					}				
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;			
		}
		
	}	

	/** 
	 * @description: unhighlight all text
	 * @todo: implement this function using the jquery extend/fn plugin system
	 *
	 */	
	function unhighlightText()
	{	
		jQuery.cookie('text_signature', null, { path: '/', expires: 1} );
		jQuery('#accordion').accordion('activate', false);
		jQuery('#selected_block').remove();		
	}
	
	function unhighlightSelection()
	{
		if(allow_text_selection)
		{	
			jQuery.cookie('text_selection', 0, { path: '/', expires: 1} );
			jQuery('#selected_text').replaceWith( jQuery('#selected_text').text() );		
			jQuery('#selected_text').remove();	
		}	
		else
		{
			return false;
		}
	}



	function getSelection(){		
		if (window.getSelection && allow_text_selection) {
 			return window.getSelection();
		}
		else{
			return false;
		}
		
	}

	function getRangeObject(selectionObject) {
		if (selectionObject.getRangeAt && allow_text_selection){
			ranges = [];
			for(var i = 0; i < selectionObject.rangeCount; i++) {
				if( i > 0){
 					selectionObject.getRangeAt(i).collapse();
				}
			}

			return selectionObject.getRangeAt(0);
		}
		else{
			return false;
		}
	}


	
	function similarString (str1, str2){		

 		var percent = 1 - levenshtein(str1, str2) / Math.max(str1.length, str2.length);
		return percent;

	}
	
	
    // http://kevin.vanzonneveld.net
	function levenshtein (a, b){
	    var min=Math.min, len1=0, len2=0, I=0, i=0, d=[], c='', j=0, J=0;

	    // BEGIN STATIC
	    var split = false;
	    try{
	        split=!('0')[0];
	    } catch(i){
	        split=true; // Earlier IE may not support access by string index
	    }
	    // END STATIC

	    if (a == b) {
	        return 0;
	    }
	    if (!a.length || !b.length) {
	        return b.length || a.length;
	    }
	    if (split){
	        a = a.split('');b = b.split('');
	    }
	    len1 = a.length + 1;
	    len2 = b.length + 1;
	    d = [[0]];
	    while (++i < len2) {
	        d[0][i] = i;
	    }
	    i = 0;
	    while (++i < len1) {
	        J = j = 0;
	        c = a[I];
	        d[i] = [i];
	        while (++j < len2) {
	            d[i][j] = min(d[I][j] + 1, d[i][J] + 1, d[I][J] + (c != b[J]));
	            ++J;
	        }
	        ++I;
	    }

	    return d[len1 - 1][len2 - 1];
	}	


	function getElementXPath(elt)
	{
	     var path = "";
	     for (; elt && elt.nodeType == 1; elt = elt.parentNode)
	     {
	   	idx = getElementIdx(elt);
		xname = elt.tagName;
		if (idx > 1) xname += "[" + idx + "]";
		path = "/" + xname + path;
	     }

	     return path;	
	}

	function getElementIdx(elt)
	{
	    var count = 1;
	    for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)
	    {
	        if(sib.nodeType == 1 && sib.tagName == elt.tagName)	count++
	    }

	    return count;
	}

	
	//if there is an anchor, scroll to it, nicely.
	if (document.location.hash.length) {
		
		jQuery('html, body').scrollTo(0, 0);
		jQuery('.container .containerBody').scrollTo( 0, 0);
		unhighlightSelection();
		
		var anchor = document.location.hash.substring(1);
		var search = document.location.search;
		var signature = false;
			
		if( !isNaN(anchor))
		{
			signature = getTextSignatureByParagraphNumber(anchor -1);
		}		
		else if( anchor.substring(0, 8) == 'comment-'){
			var commentId = anchor.substring(8);
			signature = getTextSignatureByCommentId( commentId  );			
		}		
		else if( search.length && getQueryVariable('replytocom')){
			signature = getTextSignatureByCommentId(  getQueryVariable('replytocom') );
		}
		
		if(signature != false){
			selectParagraph(signature);	
			var paragraphnumber = getCommentIdByTextSignature(signature);
			on_load_selected_paragraph = paragraphnumber;			
		}
	}

		

});


function savePosition(){
	var browser_width =  jQuery(window).width() ;
	var browser_height =  jQuery(window).height() ;
	var browser_scroll_top = jQuery(window).scrollTop();
	var commentbox_height = jQuery(this).height();
	var commentbox_top = jQuery('#commentbox').position().top;
	var commentbox_left = jQuery('#commentbox').position().left;
	var commentbox_relative_top = (commentbox_top - browser_scroll_top);

	jQuery.cookie('left_postion_commentbox', commentbox_left);
	jQuery.cookie('top_postion_commentbox', commentbox_relative_top);		
}


jQuery.fn.buildContainers = function (){
	return this.each (function ()
	{
		this.options = {
			containment:wp_path + "/wp-content/plugins/CommentPress/js/jquery/external/mbContainer/document/",
			elementsPath:wp_path + "/wp-content/plugins/CommentPress/js/jquery/external/mbContainer/elements/"
		}

		var container=$(this);
		container.find(".containerTable:first").css("width","100%");
		container.find(".c:first").wrapInner("<div class='containerBody'style='display:block'></div>");
		container.find(".n:first").attr("unselectable","on");
		var icon=container.attr("icon")?container.attr("icon"):"";
		var buttons=container.attr("buttons")?container.attr("buttons"):"";
		container.setIcon(icon, this.options);
		container.setButtons(buttons, this.options);
		if (msie6 && container.css("height")=="auto") container.find(".containerBody:first").hide();
		container.find(".containerBody:first", ".c:first").css("height",container.outerHeight()-container.find(".n:first").outerHeight()-container.find(".s:first").outerHeight());
		if (msie6 && container.css("height")=="auto") container.find(".containerBody:first").show();
		if (container.hasClass("draggable") && (!safari) ){
			container.css({position:"fixed"});
			container.find(".n:first").css({cursor:"move"});
			container.css({zIndex:zi++});
			container.draggable({handle:".n:first",cancel:".c",delay:0, containment:"document", stop: function(){ if(allow_users_to_save_position){ savePosition();  }} });
			container.bind("mousedown",function(){
				$(this).css({zIndex:zi++});
			}
				);
		}
		if (container.hasClass("resizable")){
			container.containerResize(this.options);
		}
		if (container.attr("minimized")=="true"){
			container.attr("minimized","false");
			container.minimize(this.options);
		}
		$(this).attr("minimized","false");

		if (container.attr("iconized")=="true"){
			container.attr("iconized","false");
			container.iconize(this.options);
		}
		$(this).attr("iconized","false");

	});
}
jQuery.fn.containerResize = function (){
	$(this).resizable({
		handles:$(this).hasClass("draggable") ? "":"s,e",
		minWidth: 150,
		minHeight: 150,
		helper: "proxy",
		transparent: !$.browser.msie,
		autoHide: !msie6,
		stop:function(e,o){
			var resCont=msie6 ?o.helper:$(this);
			this.elHeight= resCont.outerHeight()-$(this).find(".n:first").outerHeight()-$(this).find(".s:first").outerHeight();
			$(this).find(".containerBody:first",".c:first").css({height: this.elHeight});
		}
	});
}
jQuery.fn.setIcon = function (icon, opt){
	if (icon !="" ){
		$(this).find(".no:first").append("<img class='icon' src='"+opt.elementsPath+icon+"' style='position:absolute'>");

	}else{
		$(this).find(".n:first").css({paddingLeft:"0"});
	}
}
jQuery.fn.setButtons = function (buttons, opt){
	var container=$(this);
	if (buttons !=""){
		var btn=buttons.split(",");
		$(this).find(".ne:first").append("<div class='buttonBar' style='position:absolute'></div>");
		for (var i in btn){
			if (btn[i]=="c"){
				$(this).find(".buttonBar:first").append("<img src='"+opt.elementsPath+"close.png' class='close'>");
				$(this).find(".close:first").bind("click",function(){container.fadeOut(200)});
			}
			if (btn[i]=="m"){
				$(this).find(".n:first").attr("unselectable","on");
				$(this).find(".buttonBar:first").append("<img src='"+opt.elementsPath+"min.png' class='minimizeContainer'>");
				$(this).find(".minimizeContainer:first").bind("click",function(){container.minimize(opt)});
				$(this).find(".n:first").bind("dblclick",function(){container.minimize(opt)});
			}
			if (btn[i]=="p"){
				$(this).find(".buttonBar:first").append("<img src='"+opt.elementsPath+"print.png' class='printContainer'>");
				$(this).find(".printContainer:first").bind("click",function(){});
			}
			if (btn[i]=="i"){
				$(this).find(".buttonBar:first").append("<img src='"+opt.elementsPath+"iconize.png' class='iconizeContainer'>");
				$(this).find(".iconizeContainer:first").bind("click",function(){container.iconize(opt)});
			}
		}
		var fadeOnClose=$.browser.mozilla || $.browser.safari;
		$(this).find(".buttonBar:first img").css({opacity:.5, cursor:"pointer"}).mouseover(function(){if (fadeOnClose)$(this).fadeTo(200,1)}).mouseout(function(){if (fadeOnClose)$(this).fadeTo(200,.5)});
	}
}
jQuery.fn.minimize = function (opt){
	var container=$(this);
	if ($(this).attr("minimized")=="false"){
		this.w = container.width();
		this.h = container.height();
		container.find(".containerTable:first").css("width","100%");
		container.find(".middle:first").fadeOut("fast",function(){container.css("height","")});
		$(this).attr("minimized","true");
		container.find(".minimizeContainer:first").attr("src",opt.elementsPath+"max.png");
		container.resizable("destroy");
		jQuery.cookie('minimized', 'true', { path: '/', expires: 1}); 
		
	}else{
		container.find(".middle:first").fadeIn("slow",function(){container.css("height",container.find(".containerTable:first").height())});
		if (container.hasClass("resizable")) container.containerResize();
		$(this).attr("minimized","false");
		container.find(".minimizeContainer:first").attr("src","elements/min.png");
		jQuery.cookie('minimized', 'false', { path: '/', expires: 1}); 
	}
}
jQuery.fn.iconize = function (opt){
	return this.each (function ()
	{
		var container=$(this);
		var browser_width =  jQuery(window).width() ;
		var browser_height =  jQuery(window).height() ;
		var marginRight = 0;//= jQuery.cookie('sidebar'); 
		
		container.attr("w",container.width());
		container.attr("h",container.height());
		container.attr("t",container.css("top"));
		container.attr("l",container.css("left"));
		container.resizable("destroy");
		if (!$.browser.msie) {
			container.find(".containerTable:first").fadeOut("fast");
			container.animate({ top: "1px",left: browser_width + marginRight - 31},200);
		}else{
			container.find(".containerTable:first").hide();
			container.css({ top: "1px", left:browser_width + marginRight - 31});
		}
		container.append("<img src='"+opt.elementsPath+(container.attr("icon")?container.attr("icon"):"comments.png")+"' class='restoreContainer'>");
		container.find(".restoreContainer:first").bind("click",function(){
			if (!$.browser.msie) {
				container.find(".containerTable:first").fadeIn("fast");
				container.animate({height:container.attr("h"), width:container.attr("w"),left:container.attr("l")},200);
			} else {
				container.find(".containerTable:first").show();
				container.css({height:container.attr("h"), width:container.attr("w"),left:container.attr("l")});
			}
			container.find(".restoreContainer:first").remove();
			if (container.hasClass("resizable")) container.containerResize();			
		});
	});
}


// plugin definition
jQuery.fn.highlight = function() {
  // Our plugin implementation code goes here.
};

