function initSaveForm()
{
	var v = $("#form_save").validate({
		submitHandler: function(form) {
			// bind form using 'ajaxForm' using various options
			jQuery(form).ajaxSubmit({
				target:        '#feedback_div',   // target element(s) to be updated with server response 
				success:       saveItemCallback  // post-submit callback 
			});
		}	
		// set this class to error-labels to indicate valid fields
		,success: function(label) {
			label.addClass("checked");
		}
	});

	$("#btn_saveItem").click(function()
	{
		saveItem_formSubmit();
	});
	$('#form_cancel_link').hide();
	$("#form_cancel_link").click(function()
	{
		clearItemFormFields();
		return false;
	});	
}

function saveItem_formSubmit()
{
	var theForm = $("#form_save");
	var labels = $("#form_save").find("label");	
	var i = 0;
	if(theForm.valid()){
		$('#btn_saveItem').attr('disabled', 'disabled'); 
		$('#spinner_saveItem').removeClass("hideme");
		$('#form_save').submit();
	}
}

function saveItemCallback(responseText, statusText)  { 
	
	var labels = $("#form_save").find("label");	 
	// remove labels created by validation
	labels.each(function (i){
		$(labels[i]).remove();
	})	
	$("div#list_div .container").html(responseText);
	clearItemFormFields();//clear all fields to reset
	$('#btn_saveItem').removeAttr('disabled'); 	 
	$('#spinner_saveItem').addClass("hideme");
	$('#continue_div').show();
	$('#form_cancel_link').hide();
} 


function loadFormContents(jsonObj, id, itemtype){
	var itemToLoad = "";
	$.each(jsonObj, function(i,item) {
		if( jsonObj[i].id == id )		
		{
			itemToLoad = jsonObj[i];
		}
	});
	if(itemToLoad!= "")
	{
		$('#form_cancel_link').show(); // show cancel link
		// set form field values
		switch(itemtype){
			case 'locations' :
			{
				populateLocationForm(itemToLoad);	
				break;
			}
			case 'person' :
			{
				populatePersonForm(itemToLoad);	
				break;
			}
			case 'pet' :
			{
				populatePetForm(itemToLoad);	
				break;
			}
			case 'contact' :
			{
				populateContactForm(itemToLoad);	
				break;
			}
			case 'meetingplace' :
			{
				populateMeetingplaceForm(itemToLoad);	
				break;
			}
		}
	}
}

function clearItemFormFields()
{
	switch($("input#itemtype").val()){
		case 'locations' :
		{
			clearLocationForm();	
			break;
		}
		case 'person' :
		{
			clearPersonForm();	
			break;
		}
		case 'pet' :
		{
			clearPetForm();	
			break;
		}
		case 'contact' :
		{
			clearContactForm();	
			break;
		}
		case 'meetingplace' :
		{
			clearMeetingplaceForm();	
			break;
		}
	}
}	
/* LOCATION form fields */
function populateLocationForm(itemToLoad)
{
	var selectorSrting = "select#state option[value='"+ itemToLoad.state + "']";
	$(selectorSrting).attr("selected","selected");
	$('input#id').val(itemToLoad.id);	
	$('input#name').val(itemToLoad.name);	
	$('input#address').val(itemToLoad.address);
	$('input#city').val(itemToLoad.city);	
	setStateMenu(itemToLoad.state);
	$('input#zipcode').val(itemToLoad.zipcode);
	$('input#phones').val(itemToLoad.phones);
	$('textarea#instructions').val(itemToLoad.instructions);
	$('textarea#plan').val(itemToLoad.plan);
}
function clearLocationForm()
{
	$('input#id').val("");	
	$('input#name').val("");	
	$('input#address').val("");
	$('input#city').val("");	
	setStateMenu('Texas');
	$('input#zipcode').val("");	
	$('input#phones').val("");	
	$('textarea#instructions').val("");	
	$('textarea#plan').val("");			
}
/* PERSON form fields */
function populatePersonForm(itemToLoad)
{
	$('input#id').val(itemToLoad.id);	
	$('input#name').val(itemToLoad.name);
	$('input#ageType').val(itemToLoad.agetype);
	$('textarea#specialNeeds').val(itemToLoad.specialneeds);
	$('textarea#identifyingMarks').val(itemToLoad.identifyingmarks);		
	$("#gender option[selected='selected']").removeAttr("selected");
	$("#gender option[value='"+itemToLoad.gender+"']").attr("selected", "selected");	
}
function clearPersonForm()
{
	$('input#id').val("");	
	$('input#name').val("");
	$('input#ageType').val("");	
	$('textarea#specialNeeds').val("");	
	$('textarea#identifyingMarks').val("");	
	$("#gender option[selected='selected']").removeAttr("selected");
	$("#gender option[value='Male']").attr("selected", "selected");	
}
/* PET form fields */
function populatePetForm(itemToLoad)
{
	$('input#id').val(itemToLoad.id);	
	$('input#name').val(itemToLoad.name);
	$('input#type').val(itemToLoad.type);	
	$('input#age').val(itemToLoad.age);	
	$('textarea#description').val(itemToLoad.description);			
	$("#gender option[selected='selected']").removeAttr("selected");
	$("#gender option[value='"+itemToLoad.gender+"']").attr("selected", "selected");	
}
function clearPetForm()
{
	$('input#id').val("");	
	$('input#name').val("");
	$('input#type').val("");	
	$('input#age').val("");	
	$('textarea#description').val("");	
	$("#gender option[selected='selected']").removeAttr("selected");
	$("#gender option[value='Male']").attr("selected", "selected");	
}	
/* MEETINGPLACE form fields */
function populateMeetingplaceForm(itemToLoad)
{
	var selectorSrting = "select#state option[value='"+ itemToLoad.state + "']";
	$(selectorSrting).attr("selected","selected");
	$('input#id').val(itemToLoad.id);	
	$('input#name').val(itemToLoad.name);	
	$('input#address').val(itemToLoad.address);
	$('input#city').val(itemToLoad.city);	
	setStateMenu(itemToLoad.state);
	$('input#zipcode').val(itemToLoad.zipcode);		
	$('input#phones').val(itemToLoad.phones);
	$('textarea#instructions').val(itemToLoad.instructions);	
}
function clearMeetingplaceForm()
{
	$('input#id').val("");	
	$('input#name').val("");	
	$('input#address').val("");
	$('input#city').val("");	
	setStateMenu('Texas');
	$('input#zipcode').val("");		
	$('input#phones').val("");	
	$('textarea#instructions').val("");		
}
/* CONTACT form fields */
function populateContactForm(itemToLoad)
{
	$('input#id').val(itemToLoad.id);	
	$('input#name').val(itemToLoad.name);
	$('input#phonenumber').val(itemToLoad.phonenumber);		
}
function clearContactForm()
{
	$('input#id').val("");	
	$('input#name').val("");
	$('input#phonenumber').val("");
}



function deleteItem(postToUrl, id)
{
	var confirmMessage = "Are you sure you want to delete this item?";
	if(_LANGUAGE == "es")
	{
		confirmMessage = "&iquest;Est&aacute;s seguro de que deseas eliminar esto?";
	}
	if (confirm(confirmMessage)) {
		$("#item_" + id).remove();
		$.ajax({
			type: "post",
			url: postToUrl,
			data: {
				id: id,
				isAjaxRequest: true
			},
			beforeSend: function(){
			},
			success: function(html){
				$("div#list_div .container").html(html);
			}
		});
	}
}
	function addItemListClickEvent(itemtype, editUrl, deleteUrl)
	{
		var listItems = $("div#list_items").find("a");		
		listItems.each(function (i) {
			var thisElement = $(listItems[i]);
			var arrID = thisElement.attr("id").split("_");
			var id = arrID[1];
			var linkClass = thisElement.attr("class");
			$('#continue_div').show();
			thisElement.click(function(){
				if (linkClass == "edit") {
					loadFormContents(itemsAsJSON, id, itemtype);
				}
				if (linkClass == "delete") {
					deleteItem(deleteUrl, id);
				}
				return false;
			})
		});	
	}
	
function setStateMenu(val){
	$("#state option[selected='selected']").removeAttr("selected");
	$("#state option[value='"+val+"']").attr("selected", "selected");
}


function getStateName(abbrev){
	var state = "Texas";
	for(var i=1; i <statesAbbrev.length; i++){
		if(statesAbbrev[i].toLowerCase() == abbrev.toLowerCase()){
			state = statesNames[i];
		}
	}
	return state;
}
/* ************************************************************************************* */
/*  functions here are for displaying formatted preview and generating printable PDF	*/
/* ********************************************************************************** */
/*  clones the page table - whenever we need more than 1 printed page
	by copying our hidden page table and assigning a new page ID
*/
function clonePageTable(){
	
}

/*  loops through the user generated content (each one is a "box"),
	and determines if the height of the box will fit into the current page's current column
	if it fits, we'll add the box and increment the current column's height tracker
	if it does not fit, we'll either move it to the next column OR we'll start a new page
	and add it to the 1st column .
	
*/
function createPopulatedPages(destUrl){
	var maxPageHeight = 856; // maximum page height
	var logoContainerHeight = parseInt($("#logoHeader").height()); // grab the height of our logo/header
	var colHeightRemaining = maxPageHeight - logoContainerHeight;
	var currentPageNum = 1; // which page is currently being populated
	var currentPageColNum = 1; // tracks which column is currently being populated
	var currentPageColHeight = 1; // tracks the height of the current page's current column
	var currentBox = ""; // to contain a box reference while looping through all boxes
	var currentBoxHeight = ""; // to contain the current box's height
	var boxArray = $("div.box");
	var boxCount = boxArray.length; // total number of content boxes
	var pageColCount = 4; // total number of columns on a page
	var placeHolderText = "<!-- [PAGEBREAK] -->";
	// loop through all boxes
	for(var i=0; i <boxCount; i++){
		currentBox = $(boxArray[i]); // grab instance of current box
		currentBoxHeight = currentBox.height(); // get current box height
		currentPageId = "pg_" + currentPageNum;	
		currentPageHeight = $(currentPageId).height();
			
		// determine if box will fit into current colum of current page
		if(colHeightRemaining >= currentBoxHeight && currentPageHeight < maxPageHeight)
		{
			// SAME COLUMN LOGIC - box DOES fit... so add the box to the table td as html and subtract the height	
			// subtract the box height from the remaining col height
			colHeightRemaining -= currentBoxHeight;
			// set which page col to populate
			currentColToFill = "#pg_" + currentPageNum + "_col_" + currentPageColNum;
			$(currentColToFill).append( currentBox );
		}
		else
		{
			// NEW COLUMN LOGIC- box does NOT fit... 
			currentPageColNum++; //increment out current page col number
			// We only need to substract logo height if we are on page 1
			if (currentPageNum > 1) {
				logoContainerHeight = 0;
			};
			colHeightRemaining = maxPageHeight - logoContainerHeight; // reset the height
			// have we exceeded the page col count? if so, we need to add a page and start over	(with col 1)
			if(currentPageColNum > pageColCount)
			{
				currentPageColNum = 1; // reset the column number		
				var currentPageTable = "#pg_" + currentPageNum;
				// var currentPageTable = $('.pages_wrap:first')
				var clonedTable = $('.pages_wrap:first').clone();// clone the table
				var clonedTableId = "pg_" + (currentPageNum+1);
				// remove elements from old table
				clonedTable.attr("id", clonedTableId); // updating table id
				if(currentPageNum == 1)
				{
					$(clonedTable).find("tr:first").remove(); // removing first tr (only need to do this for table 1)
				}
				currentPageNum++; // increment the page count
				var tds = $(clonedTable).find("td"); 
				for (var x=0; x < tds.length; x++) {					
					$(tds[x]).attr("id", clonedTableId + "_col_" + parseInt(x + 1));// updating td ids
					$(tds[x]).html(""); // updating old content
				};
				$(placeHolderText).appendTo("#pages");
				$(clonedTable).appendTo("#pages");
		
			}
			
			
			// subtract the box height from the remaining col height
			colHeightRemaining -= currentBoxHeight;
			// set which page col to populate
			currentColToFill = "#pg_" + currentPageNum + "_col_" + currentPageColNum;
			$(currentColToFill).append( currentBox );
		
		}		
		
	}
	createPDF(destUrl);
}

function createPDF(destUrl){
	var linkSrc = $("#download_plan a").attr("href");
	var data = {
	  pagecontent: $("#pages").html()
	};
	
	 $.ajax({
	   type: "POST",
	   url: destUrl,
	   data: data,
	   success: function(msg){
		msg = $.trim(msg);
		 $("#processing_plan").hide();
		  $("#download_plan a").attr("href", linkSrc + msg);
		 $("#download_plan").show("fast");
	   }
	 });
}
/* ***************************************************************** */