//Script:	FeedbackLite.js
//Author:	Ken Le
//Purpose:  Provide a feedback dialog and save text to a SharePoint list
//Dependencies:
//	jquery.js
//  jpoint.js
//	jquery-ui-1.7.1.redmond.css
//	jquery-ui.js
//List required fields:
//	Title - single line text - holds instant ID
//	Comments - multi lines text - holds feeback text
//  PageUrl - single line text - holds source page url
/************************************************************************
//Example 1:
//Insert the feedback dialog form at the target div
<script type="text/javascript" src="/eon/com/Res/jsSharepoint/temp/jWebpart_template.js" ></script>
<script type="text/javascript" src="/eon/com/Res/jquery/jquery-ui/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/eon/com/Res/jquery-ui-1.7.1.redmond/css/redmond/jquery-ui-1.7.1.redmond.css" />
<script type="text/javascript" src="/eon/com/Res/jPoint_Dev/webparts/jPart.feedbackLite.js" ></script>
<table width="50%" align="center">
  <tr><td><div id="FeedbackLiteDiv"></div></td></tr>
</table>
<!-- config options using GUI
<script type-"text/javascript">
$(document).ready(function() {
    FeedbackLite({
        ID:"FeedbackBox1"
        ,TargetDiv:"FeedbackLiteDiv"
        ,SiteURL:"/eon/dev/ken/"
        ,ListName:"SurveyList"
        ,TextAreaRows: 5
        ,MessagePrompt:"<b>Enter your feedback comments:</b>"
        ,MessageSuccess:"Feedback sent"
        ,Title:"EON Feedback"
    });
});
</script>
-->
*************************************************************************/
/************************************************************************
//Example 2: 
//Insert the feedback dialog button using callback
//Sample default options (configure with configUI)
//	{ID:'FeedbackLite'
//	,TargetDiv:'FeedbackLiteDiv'
//	,SiteURL:'/eon/dev/ken'
//	,ListName:'SurveyList'
//	,TextAreaRows:'6'
//	,MessagePrompt:'<b>Please take a moment to provide us some feedback:</b>'
//	,MessageSuccess:'Thank you for your comment'
//	,Title:'Feedback'
//	,LinkButton:'true'
//	,LinkButtonText:'Give us your feedback'
//	,PopupDialogWidth:'400'
//	,CallBackFunction:'LoadFeedback'};
<script type="text/javascript" src="//sharejpoint.com/src/jpoint/jPointLoader.js" ></script>
<script type="text/javascript" src="//sharejpoint.com/src/jquery/jquery-ui/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//sharejpoint.com/src/jquery-ui-1.7.1.redmond/css/redmond/jquery-ui-1.7.1.redmond.css" />
<script type="text/javascript" src="//sharejpoint.com/src/jPoint/webparts/jPart.feedbackLite.js" ></script>
<script type-"text/javascript">
function LoadFeedback() {
  $(document).ready(function() {
    var tbody = $(".ms-searchform").children("tbody")
    var thtml = tbody.html();
    tbody.html(thtml + "<div id='InsertedDiv'>");
    var tpos = tbody.offset();
    $("#InsertedDiv").css({'position':'absolute','top':tpos.top+15})

    if (myjLocalOptions != undefined) {
      FeedbackLite(myjLocalOptions);

      var fbtitle = $("#InsertedDiv span:contains('Give us your feedback')")
      $("#FBTITLE").css({'white-space':'nowrap','color':'orange','font-size':'8pt'})
      fbtitle.hide("slow")
      fbtitle.show("slow")
      fbtitle.hide("slow")
      fbtitle.show("slow")
    }
  });
}
</script>
*************************************************************************/

//field, description, default value
myjPart.ShowConfigDefaults = [
	["ID", 				"Unique identifier for plugin", 	"FeedbackLite"]
	,["TargetDiv",		"HTML DIV to hold the dialog",		""]
	,["SiteURL",		"Site URL of feedback list",		""]
	,["ListName",		"List name of feedback list",		""]
	,["TextAreaRows",	"Number of rows to display for text input","6"]
	,["MessagePrompt",	"Prompt message for text input",	"<b>Please take a moment to provide us some feedback:</b>"]
	,["MessageSuccess",	"Message to display on submit",		"Thank you for your comment"]
	,["Title",			"Popup dialog title (optional)",	"Feedback"]
	,["LinkButton",		"Display feedback button (optional)","false"]
	,["LinkButtonText",	"Feedback button title (optional)",	"Give us your feedback"]
	,["PopupDialogWidth","Popup dialog width (optional)",	"400"]
	,["CallBackFunction","Callback function (optional)",	""]
	];

myjPart.setjPartOptions({Plugin:{
	Name:'Feedback Lite'
	, Version:'2.0'
	, Origin:'SharejPoint'
	, Description:'Popup dialog to prompt for user input and save to a target list.'
	, Developer:'Ken Le'
}});

//Start Webpart logic code -----------------------------------
$(document).ready(function() { //Wait page to load and then apply webpart logic
	if(myjParts[JpartProcessing] != null)
	{
		var thisWebpart = myjParts[JpartProcessing];
		
		try
		{
			//jPart user code goes here ---------------------------
			if(thisWebpart.Options.Local != null)
			{
				if (thisWebpart.Options.Local.CallBackFunction != "")
					window[thisWebpart.Options.Local.CallBackFunction].call();			
				else
					FeedbackLite(thisWebpart.Options.Local);
			}		
					
			//-----------------------------------------------------
		}catch(err){};
		JpartProcessing = JpartProcessing + 1;
	}
});
//End Webpart logic code -----------------------------------
///////////////////////////////////////////////////////////////////////////////////////////
//Main FeedbackLite
function FeedbackLite(options)
{
    //Default options    
    this.defaults = {
        ID: "FeedbackID"     				//Unique ID for this Feedback instant
        ,TargetDiv: "TargetDiv"     		//div id to contain feedback GUI
        ,SiteURL: "/eon/"                   //Absolute path to list
        ,ListName: "FeedbackListName"       //SP list name hosting chat
        ,TargetFields: ["Title","Comments"]
        ,Title: "EON Feedback"           	//dialog title
        ,TextAreaRows: "5"
        ,MessagePrompt: "Please enter your feedback comments:"  //instruction message
        ,MessageSuccess: "Feedback sent"           				//success message
        ,LinkButton: "false"					//Add link button to activate dialog
        ,LinkButtonText: "Feedback"           				//text of link button
        ,PopupDialogWidth: "500"
    };

    //Update defaults with user provided options
    this.thisOpt = $.extend(this.defaults, options);
    
	//$.debug(thisOpt.Debug); //false by default
	//$.loglevel(thisOpt.LogLevel); //0 by default
	
	this.jpoint = jP;
	
	var fullURL = document.location.protocol + "//" + document.location.host + thisOpt.SiteURL + "";
	this.spObj = this.jpoint.Lists.setSPObject(fullURL, thisOpt.ListName);

	//Main function
	InitFeedbackGUI();
	
	//Functions

	//Create feedback GUI form
	function InitFeedbackGUI()
	{
	
		//Get target div, if none use body
	    var targetDiv = $("#"+thisOpt.TargetDiv);
	    if (targetDiv==null)
	    {
	        var body = document.body;
	        thisOpt.TargetDiv = "FeedbackLiteDiv2";
	        targetDiv = CreateElement(body, "div", thisOpt.TargetDiv)
	    }
	    
	    //Get current TargetDiv html
		var curHtml = $("#"+thisOpt.TargetDiv).html();
    
    	//Construct dialog html
		var html = "";
		
		//Add dialog button if LinkButton option is true
		if (thisOpt.LinkButton == "true") 
		{
			html += "<div id='"+thisOpt.ID+"_Open"+"' style='{color:#83b0ec;cursor:hand}'>";
			html += "<table border=0>";
			html += "<tr>";
			html += "<td><span id='"+thisOpt.ID+"_Button"+"' class='ui-icon ui-icon-comment' ></span></td>";
			html += "<td><span style='{color:#83b0ec;cursor:hand;font-family:verdana,arial,helvetica,sans-serif; font-size:8pt;}'>"
				+ "<table cellspacing=0 cellpadding=0><tr><td id=FBTITLE >"+thisOpt.LinkButtonText+"</td></tr></table>"
				+ "</span></td>";
			html += "</tr>";
			html += "</table>";
			html += "</div>";
		}
		//Add dialog body
		html += "<div id='"+thisOpt.ID+"_Dialog"+"' title='"+thisOpt.Title+"'>";
		html += "<table width='100%' border=0 id='"+thisOpt.ID+"_DialogTable'>";
		html += "<tr>";
		html += "<td colspan=2 id='"+thisOpt.ID+"_InstructionMsg'>"+thisOpt.MessagePrompt+"</td>";
		html += "</tr>";
		html += "<tr>";
		html += "<td colspan=2><textarea id='"+thisOpt.ID+"_CommentInput' rows='"+thisOpt.TextAreaRows+"' cols='46' maxlength='256' style='{width:100%}'></textarea></td>";
		html += "</tr>";
		html += "<tr>";
		html += "<td width='90%'><div id='"+thisOpt.ID+"_Status'></div>&nbsp;</td>";
		html += "<td align=right><input id='"+thisOpt.ID+"_Send' type='button' value='Send' /></td>";		
		html += "</tr>";
		html += "</table>";
		html += "</div>";
		
		//Add to DOM at TargetDiv		
		$("#"+thisOpt.TargetDiv).html(html);	  
		
		//Add Send button onclick action
    	$("#"+thisOpt.ID+"_Send").click(fAddFeedbackMessage(spObj, thisOpt.ID, thisOpt.MessageSuccess));
    	
		//Set up dialog button action if LinkButton is true
		if (thisOpt.LinkButton == "true") 
		{
			//$.ui.dialog.defaults.bgiframe = true;
			var diag = "#"+thisOpt.ID+"_Dialog";				

			//Adjust offset so not to go off page
		    var pos = $("#"+thisOpt.ID+"_Button").offset();
		    var offsetwith = $(document.body).width() - pos.left;
		    var leftoffset = 20;
		    if (offsetwith < parseInt(thisOpt.PopupDialogWidth)) leftoffset = -1 * parseInt(thisOpt.PopupDialogWidth) + 100;
		  
			//set options	      
			$(diag).dialog();
		    $(diag).dialog('option', 'position', [pos.left+leftoffset,pos.top+20]);
		    $(diag).dialog('option', 'width', parseInt(thisOpt.PopupDialogWidth));
		    $(diag).dialog('option', 'show', 'fold');	    
		    $(diag).dialog('option', 'closeOnEscape', true);
		       
	    	//Modify style
	    	var sStyle = "font-family:verdana,arial,helvetica,sans-serif; font-size:8pt;";
	    	$("#"+thisOpt.ID+"_InstructionMsg").attr("style", sStyle);
	    	$("#"+thisOpt.ID+"_CommentInput").attr("style", sStyle + "width=100%");
	    	$("#"+thisOpt.ID+"_Status").attr("style", sStyle);
	    	$("#"+thisOpt.ID+"_Send").attr("style", sStyle);


			//Set click event			
	    	$("#"+thisOpt.ID+"_Open").click(fOpenDialog(thisOpt.ID));

			//close for now
	        $(diag).dialog('close')
		}
	}
	//Construct open dialog function for onclick action
	function fOpenDialog(sID)
	{
		return function(){
		    $("#"+sID+"_Status").html("");	//clear status
			$("#"+sID+"_Dialog").dialog('open')  //open previously closed dialog
			$(".ui-widget-shadow").hide();	//hide shadow
			//$("#"+sID+"_CommentInput").get(0).focus();
			//$("#"+sID+"_DialogTable").css("width", "100%")
		}
	}
	//Construct send feedback function for button click action
	function fAddFeedbackMessage(spObj, sID, sSuccessMsg)
	{
		return function() {
			//get feedback message, return if blank
		   	var FeedbackMsg = $("#"+sID+"_CommentInput").val();
		   	if (FeedbackMsg == "") return;
		   	
		   	FeedbackMsg = FeedbackMsg.replace(/[\n\s]/g, " "); //remove newline char
		   	$("#"+sID+"_CommentInput").val(""); //clear comment field
		   	
		    //Add new entry
		    var entryData = [{ Title:sID, Comments:FeedbackMsg, PageUrl:window.top.location.href }]
		    spObj.addItem(entryData);
		    
		    //Update status
		    $("#"+sID+"_Status").html("<font color=red>"+sSuccessMsg+"</font>")
	    }
	}
	//Create DOM element
	function CreateElement(parent, type, id, classname) {
	  var elem = document.createElement(type);
	  if (id)
	    elem.setAttribute("id", id);
	  if (classname)
	    elem.setAttribute("className", classname);
	  parent.appendChild(elem);
	  return elem;
	}
}

