/**
 * @package		LQM Component
 * @subpackage	Assets
 * @version		$Id: default.js 617 2008-11-25 17:13:24Z tcp $
 * @copyright	Copyright (C) 2006 - 2007 Green Mountain Information Technology and Consulting. All rights reserved.
 * @author		tcp@gmitc.biz
 */


function lqmOpenDiv(href, divName)
{

	var div = document.getElementById(divName);

	if ( ! div ) 
	{
		alert('Cannot find the target div ' + divName + ' in the page');
		return false;
	}
	
	div.innerHTML = '';
	
	try {
		Zapatec.Transport.fetch({
			url: href,
			//busyContainer: "<?php echo $formID ?>",
			// Onload event handler

			onLoad: function(objRequest) {
				
				// Put fetched fragment into "divName" div
				Zapatec.Transport.setInnerHtml({
					html: objRequest.responseText,
					container: div
				});
			}
		});
	} catch(err) {
		return false;
	}
	
	return false;
}


function lqmFetchResults(config) {
	// Fetch HTML fragment
	//alert('url is '+urlName+' and divName is '+divName);

	var url = config.url + '&loadZpGridLibrary=0' + '&' + Math.random();
	Zapatec.Transport.fetch({
		// URL to fetch
		//url: encodeURI(urlName + '&' + Math.random()),
		url: url,
		busyContainer: config.container,
		// Onload event handler
		onLoad: function(objRequest) {
			var target = document.getElementById(config.target);
			// Put fetched fragment into "divName" div
			Zapatec.Transport.setInnerHtml({
				html: objRequest.responseText,
				container: target
			});
		}
	});
}

lqmSubmitForm = function lqmSubmitForm(config)
{

	var elementNamePattern	= /-\d+$/;
	var form = this.config.form;
	
	try {
		
		// An array of url arguments
		var arrUrlArgs			= [];
		
		// A suffix used to generate the submit name
		var inputSuffix			= '[]';
		
		// An array indicating a argument has been processed already
		var arrSubmitAlready	= [];
		
		// An array of Zap form elements
		var objFormElements = Zapatec.Form.Utils.getFormElements(form.id);

		this.toggleSubmits(true);
		
		for (var iElm = 0; iElm < objFormElements.length; iElm++) {
			
			// Get the current element
			var formEl = objFormElements[iElm];
			
			// Get some basic information about the element
			var elementName		= formEl.name;
			var elementValue	= formEl.value;
			var elementType		= formEl.type.toLowerCase();
			var elementNode		= formEl.nodeName.toLowerCase();
			var elementDisabled	= formEl.disabled;
			
			// Check if we're working with form elements that will contain input
			if ( !( elementNode == 'input' || elementNode == 'select' || elementNode == 'textarea' || elementNode == 'button' ) )
			{
				continue;
			}
			
			// Ignore disabled inputs, or those without a name
			if ( ! elementName || elementDisabled ) 
			{
				continue;
			}
			
			// Don't worry about radio or checkboxes that have not been selected
			if ( ( elementType == 'radio' || elementType == 'checkbox' ) && !formEl.checked )
			{
				if ( arrSubmitAlready[elementName] === undefined )
				{
					elementValue = '';
				} else {
					continue;
				}
			}
			
			// Remove any -1 or -4 produced by the multiple feature
			var submitName = elementName.replace(elementNamePattern,'') + inputSuffix;
			
			// Note the fact that we have submitted this already
			arrSubmitAlready[elementName]	= true;
			
			// Add the data to our URL string
			if ( elementType == 'select-multiple' )
			{
				// Special handling for select-multiple
				var selectOptions = formEl.options;
				for (var iOption = 0; iOption < selectOptions.length; iOption++) {
					var selectOption = selectOptions[iOption];
					if ( selectOption.selected )
					{
						//arrUrlArgs.push( submitName + '=' + escape(selectOption.value));
						arrUrlArgs.push( submitName + '=' + encodeURIComponent(selectOption.value));
					}
				}
			}
			else
			{
				// Standard input handling for other form elements
				arrUrlArgs.push( submitName + '=' + encodeURIComponent(elementValue) );
			}
		}
	
		var strContent = arrUrlArgs.join('&');
		//alert('string is ' + strContent);
		var url = form.action+'&'+strContent;
		var div = form.target;
	
		lqmFetchResults( { url: url, target: div, id: form.id } );
	} catch(e) {
		alert(e.message);
	}
	
	// Assume two second delay, then enable the submit button again
	setTimeout('Zapatec.Widget.getWidgetById('+this.id+').toggleSubmits(false)', 2000);
	
	return false;
}

function lqmOnObjGridCellEdited(oArg)
{

	// Basic sanity checks
	var oCell		= oArg.cell;
	var pCell		= oCell.previousState;
	var newValue	= oCell.c; //this.getCellValue(oCell);
	var prevValue	= pCell.c; //this.getCellValue(pCell);

	//alert('newValue is ' + newValue + ', prevValue is ' + prevValue);

	// Don't update if the new value is undefined
	if ( newValue == undefined ) { newValue = oCell.v; }
	if ( newValue == undefined ) { return false; }

	// Don't update if the values are the same
	if ( prevValue == undefined ) { prevValue = pCell.v; }
	if ( newValue == prevValue ) { return false; }

	// Get the current information
	var url 		= this.config.updateQueryUrl+'&format=editgrid';
	url += '&' + [
		'lqm_column=' + this.getCellId(oCell),
		'lqm_row=' + this.getCellRowId(oCell),
		'lqm_new=' + encodeURIComponent(newValue),
		'lqm_previous=' + encodeURIComponent(prevValue)
	].join('&');

	// Get the previous information
	/*
	var oCellP	= oArg.previousState;
	url += '&' + [
		'lqm_previous_i=' + this.getCellId(oCellP),
		'lqm_previous_r=' + this.getCellRowId(oCellP),
		'lqm_previous_o=' + encodeURIComponent(this.getCellValue(oCellP))
	].join('&');
	*/

	// Get the unique id
	var oCellO	= this.getCellById(oCell.r, this.config.recIdPosition);
	url 		+= '&lqm_rid=' + this.getCellValueOriginal(oCellO);

	//alert(url);

	var oGrid = this;
	Zapatec.Transport.fetch({
		// Server-side script
		url: url,
		// Use GET method
		method: 'GET',
		// Arguments string
		content: '',
		// onLoad handler
		onLoad: function(oRequest) {
			var fCallback = oGrid.config.callbackAutoSaveCell;
			oDiv = document.getElementById(oGrid.config.messageDivId);
			if (typeof fCallback == 'function' && !fCallback({request: oRequest, oDiv: oDiv})) {
				// Cancel editing
				oCell = oGrid.revertCell({
					cell: oCell
				});
				// Show previous state
				oGrid.refreshCell({
					cell: oCell
				});
				// Inform listeners about error
				oGrid.fireEvent('gridCellNotSaved', {
					cell: oCell,
					request: oRequest
				});
			} else {
				// Inform listeners about success
				oGrid.fireEvent('gridCellSaved', {
					cell: oCell,
					request: oRequest
				});
			}
		},
		// onError handler
		onError: function(oError) {
			// Cancel editing
			oCell = oGrid.revertCell({
				cell: oCell
			});
			// Show previous state
			oGrid.refreshCell({
				cell: oCell
			});
			// Inform listeners about error
			oGrid.fireEvent('gridCellNotSaved', {
				cell: oCell,
				error: oError
			});
		},
		// Show "Saving" animated GIF
		busyContainer: this.container,
		// Use standard "Saving" animated GIF
		busyImage: 'zpsaving.gif'
	});
}


function lqmCheckServerResponseObjGrid(oArg) {
	// Get XMLHttpRequest object
	var oRequest = oArg.request;
	var oDiv = oArg.oDiv;

	// Check response
	if ( ! oRequest || ! oRequest.responseText) {
		oDiv.innerHTML = 'An invalid response from the server was received';
		return false;
	}

	// Convert data into an object
	var oJson = Zapatec.Transport.parseJsonStr(oRequest.responseText);

	if ( oDiv ) {
		Zapatec.Transport.setInnerHtml({
			html: oJson.message,
			container: oDiv
		});
		//oDiv.innerHTML = oJson.message;
	}

	if ( oJson.code == 'ok' ) {
		return true;
	}

	return false;
}

function lqmClearForm(form){
	//form.reset();
	var tags=form.getElementsByTagName("input");
	var i;
	for(i=0;i<tags.length;i++){
		 switch (tags[i].type.toUpperCase()){
			case "TEXT":
			tags[i].value="";
			break;
			case "CHECKBOX":
			tags[i].checked=false;
			break;
			case "RADIO":
			tags[i].checked=false;
			break;
		}
	 }
	 tags=form.getElementsByTagName("textarea");
	 for(i=0;i<tags.length;i++){
		tags[i].value="";
	 }
	 tags=form.getElementsByTagName("option");
	 for(i=0;i<tags.length;i++){
		tags[i].selected=false;
		tags[i].parentNode.selectedIndex=0;
	 }
}

function fromTimestamp(iTimestamp) {
	var iTime = Math.round(iTimestamp) * 1000;
	var oDate = new Date(iTime);
	var sMonth = oDate.getMonth() + 1;
	if (sMonth < 10) {
		sMonth = '0' + sMonth;
	}
	var sDay = oDate.getDate();
	if (sDay < 10) {
		sDay = '0' + sDay;
	}
	var sYear = oDate.getYear();
	if (sYear < 1900) {
		sYear += 1900;
	}
	sYear += '';
	//sYear = sYear.substr(2);
	return sMonth + '/' + sDay + '/' + sYear;
};