// common javascript used throughout Satori ContentManager websites. Written by Terry Ambrose, Satori Web Design, 2011/09/12

// the page variable is used for jquery processing in all jquery files
var page=document.location.href;
page=page.replace("#","");// we'll post back to the originating page
if(document.domain=='kiwaniswebsites.org'){
	var temppage=page.split('?');
	page=temppage[0];
}
	function getAjaxRequest(id,data){
		var ajaxrequest;
	//	if(console){console.log("the id in getAjaxRequest is " + id + " and the data attribute is " + data);}
		if($('#' + id).hasClass('callapp')){
			ajaxrequest="/apps/" + data;
		}
		return ajaxrequest;
	}

	// javascript functions are located in swd-js-core.js
	function validateFormTest(formid,data,jsonparameters){// rules and messages are specified as part of the form with class and title attributes. data represents the entered data and formdata is the attribute array from the calling file
		
		if(document.domain=="kiwaniswebsites.org"){
			if(console){
				console.log('input logged in formValidate the received values are formid= ' + formid + ',data=' + data + ', and jsonparameters=' + jsonparameters + ' for page ' + page);
			}
		}
		var v = $("#" + formid).validate({
			debug:true,
			success:function(label){
					if(!label.hasClass('success')){
						label.html("<img src='http://satoricontentmanager.net/filelib/icons/ok.png'>").addClass('success');
				}
				},
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					url: page,
					data:{// the jsonparameters when coming from loadform are the data element of the clicked item that loaded the form
						ajaxrequest:$('#' + formid).attr('data'),
						jsonparameters:jsonparameters
					},
					success:function(data){
						processResponse(data);
					}
				});
			}
		});


	}


	// javascript functions are located in swd-js-core.js
	function validateForm(formid,data,jsonparameters){// rules and messages are specified as part of the form with class and title attributes. data represents the entered data and formdata is the attribute array from the calling file
	/*	if(document.domain=="kiwaniswebsites.org"){
			alert('input logged the received values are formid= ' + formid + ',data=' + data + ', and jsonparameters=' + jsonparameters + ' for page ' + page);
		}
	*/	
		var v = $("#" + formid).validate({
			success:function(label){
					if(!label.hasClass('success')){
						label.html("<img src='http://satoricontentmanager.net/filelib/icons/ok.png'>").addClass('success');
				}
				},
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					url: page,
					data:{// the jsonparameters when coming from loadform are the data element of the clicked item that loaded the form
						ajaxrequest:$('#' + formid).attr('data'),
						jsonparameters:jsonparameters
					},
					success:function(data){
						processResponse(data);
					}
				});
			}
		});

	}

	function processResponse(data){// handles the different responses from processing
	//	if(document.domain=="kiwaniswebsites.org"){console.log('data received in processResponse function is ' + data);}
		var response = JSON.parse(data);
		var content=decodeString(response.string);// new dialog content
	
		if(response.action=="updates"){
			updateElements(response.fields);
		}
		
		if(response.closedialogs){
			// we need to close old dialog boxes
			jsonCloseDialogs(response.closedialogs);
		}
		
		if(response.dialogaction=="close"){
			$('#' + response.dialogid).dialog('close');
		}
		else if(response.dialogaction=="update" || response.dialogaction=='updates'){
		//	if(console){console.log('found dialog action of ' + response.dialogaction + ' and will create dialog for ' + response.dialogid + ' with title of ' + response.title);}
			// check to see if we need to create the dialog 
			if(!$('#' + response.dialogid).hasClass('.ui-dialog-content')){
				//if(document.domain=="kiwaniswebsites.org"){console.log('dialog ' + response.dialogid + ' created');}
				// create the dialog
				jsonMakeDialog(response,response.triggerid);
			}

			// changelog 2012/01/27 added the following to allow for form creation
			if($('#' + response.triggerid).hasClass('isform')){
			//	if(console){console.log('class isform found and form being added to ' + response.triggerid);}
				content=jsonMakeForm(response,content);
			}

			if(response.title && !response.dialogtitle){response.dialogtitle=response.title;}
			if(!response.dialogtitle && !response.title){response.dialogtitle='Processing Results';}	
					
			$('#' + response.dialogid).html(content).dialog('option','title',response.dialogtitle).dialog('open');// this option leaves the dialog box open, updates elements on the page and adds new content to the dialog

			if(response.setcluetip){
			//	if(console){console.log('setcluetip found and cluetip is being added to ' + response.dialogid);}
				var thezindex=$('#' + response.dialogid).dialog( "option", "zIndex" ) + 10;
				setClueTip(response.setcluetip,thezindex);
			}
		}

		if(response.alert){
			alert(content);
		}
		
		if(response.action=='reload'){
			alert(response.string);
			location.reload();
		}						
	}


function makeJSONString(data){
	var darray=data.split(",");// split the comma-separated list
	var datalen=darray.length;// get the length
	var jsonstring="{";// initialize the string
	for(x=0;x<datalen;x++){// iterate through the array
		if(jsonstring.length>1){jsonstring=jsonstring + ",";}// add a comma for subsequent calls
		jsonstring=jsonstring + "'" + darray[x] + "':'";// add the key
		if($('#' + darray[x].is('input'))){// add the variable if input
			jsonstring=jsonstring + $('#' + darray[x].val());
		}
		else{// add the variable if html
			jsonstring=jsonstring + $('#' + darray[x].html());
		}
		jsonstring=jsonstring + "'";// close the string
	}
	jsonstring=jsonstring + "}";// close the expression
	return jsonstring;// return the result
}

function jsonCloseDialogs(closedialogs){
	var dialogidstring=closedialogs;
	var darray=dialogidstring.split(',');
	var dcount=darray.length;
	for(x=0;x<dcount;x++){
		$('#' + darray[x]).dialog('close');
	}
}

function jsonMakeDialog(jsondata,linkid){
	/* this function:
		1) looks for a div with the id of "dialogid", which will be included in the jsondata
		2) uses the element's title attribute to set the title of the dialog
		3) if the element has a class of target-"x" in the classes, it sets a target for the dialog box, otherwise the dialog goes after loadingMessage
		4) it constructs the dialog, but does not add content
	*/

	linkid="#" + linkid;
	var targetid;
	var dialogid;
	
	if(jsondata.dialogid){
		dialogid=jsondata.dialogid;
	}
	else{
		dialogid='dialog';
	}

	if(!$('#' + dialogid).is("div")){
		
		if(jsondata.dialogclass){// set the classes for the dialog
			dialogclass=jsondata.dialogclass;
		}
		else{
			dialogclass='defaulttext';
		}
		
		// set the location of the dialog box, which will be either after an element specified by targetid (in jsondata) or the default of loadingMessage
		if(jsondata.targetid){
			targetid=jsondata.targetid;
		}
		else{
			targetid='loadingMessage';
		}
		
		$('#' + targetid).after("<div class='" + dialogclass + "' id='" + dialogid + "' style='text-align:left'></div>");// create the box
	}

	var title=$(linkid).attr('title');
	if(jsondata.title){
		title=jsondata.title;
	//	if(console){console.log('title found and set as ' + title);}
	}

	if(jsondata.debug){
		title=title + '**debugging ' + dialogid + '**';
	}

	if(jsondata.width){
		boxwidth=jsondata.width;
	}
	else{
		boxwidth=600;
	}

	// removed the close button from dialogs on 2011/09/18
	$('#' + dialogid).dialog({
		autoOpen: false,
		width: boxwidth,
		modal:true,
		show:'blind',
		hide:'blind',
		title:title
	});
	
//	if(console){console.log('creating dialog with id ' + dialogid + ' after element ' + targetid + ' and title of ' + jsondata.title);}

}

function setClueTip(tipclass,thezindex){
	// sets the basic cluetip function in a dialog where the content for the tip is in the dialog content as a | separated string. Use the JSON Handling >> Cluetip Link to implement
	if(tipclass==''){
		tipclass='cluetip';
	}
	
	$('.' + tipclass).cluetip({
		splitTitle:"|",
		cluezIndex:thezindex
	});


}

function jsonMakeForm(jsondata,content){
	if(jsondata.debug){console.log("Debug on in jsonMakeForm. Value of formid is " + jsondata.formid + " and formdata is " + jsondata.formdata + ' if variables are not appearing in the form, make sure they are included in the response array that is json encoded and echoed.');}
	
	if(jsondata.formid){
		formid=jsondata.formid;
	}

	if(jsondata.formintro){
		formintro=decodeString(jsondata.formintro);
	}
	else{
		formintro='';
	}

	if(jsondata.formclass){
		formclass=jsondata.formclass;
	}
	else{
		formclass='';
	}
	
	if(jsondata.formdata){
		formdata=jsondata.formdata;
	}
	else{
		formdata='';
	}
	
	if(jsondata.formaction){
		formaction=jsondata.formaction;
	}
	else{
		formaction='#';
	}
	
	if(jsondata.buttonvalue){
		buttonvalue=jsondata.buttonvalue;
	}
	else{
		buttonvalue='Submit';
	}

	if(jsondata.buttonid){
		buttonid=jsondata.buttonid;
	}
	else{
		buttonid='';
	}
	
	if(jsondata.buttondata){
		buttondata=jsondata.buttondata;
	}
	else{
		buttondata='';
	}
	
	if(jsondata.buttontype){
		buttontype=jsondata.buttontype;
	}
	else{
		buttontype='submit';
	}
	
	if(jsondata.buttonclass){
		buttonclass=jsondata.buttonclass;
	}
	else{
		buttonclass='';
	}
		
	if(jsondata.debug){
		diagnostics="<div id='validationresults'>Diagnostics on from test class!<br></div>";
	}
	else{
		diagnostics='';
	}

	if(jsondata.closedialog){
		closedialog=jsondata.closedialog;
	}
	else{
		closedialog='';
	}
	
	formcontent="<form class='" + formclass + "' id='" + formid + "' name='" + formid + "' method='post' action='" + formaction + "' data='" + formdata + "' >" + diagnostics + formintro + content + "<p><input type='" + buttontype + "' class=' " + closedialog + " " + buttonclass + " ' id='" + buttonid + "' value='" + buttonvalue + "' data='" + buttondata + "'></p></form>";
	
	return formcontent;
}

