
function rowCount(){
	if($('.header').length){
 		var leadid = $("input#leadid").val();
		var tbheight = 0;
		var smallheight = 178;
		var largeheight = 498;
		$('div.sfhtData > table > tbody > tr').each(function(){
			tbheight += $(this).height();
		});
		var deftbheight = $(".sfhtData").height();
		var numrows = $("div.sfhtData > table > tbody > tr").size() - 1;
		if(tbheight < deftbheight | tbheight < smallheight){
			$(".sfhtData").css("height",tbheight+"px");
		}else if(leadid!='none' && leadid!=''){
			$(".sfhtData").css("height",smallheight+"px");
		}else{
			if(tbheight > largeheight){
				$(".sfhtData").css("height",largeheight+"px");
			}else{
				$(".sfhtData").css("height",tbheight+"px");
			}
		}
		return numrows;
	}
}

function leadTimer(){
	if(typeof(timer)!='undefined'){
		clearTimeout(timer);
	}
	timer = setTimeout('getLeads()',1000);
}

function cityTimer(fieldname){
	if(typeof(citytimer)!='undefined'){
		clearTimeout(citytimer);
	}
	citytimer = setTimeout('cityLookup("'+fieldname+'")',500);
}

function cityLookup(fieldname){
	var fieldname_arr = fieldname.split('_');
	var zipcode = $("input[name="+fieldname_arr[0]+"]").val();
	if($("input[name="+fieldname_arr[1]+"]").val()==''){
		$.ajax({
				async: false,
		    url: '../include/citylookup.php',
		    type: 'POST',
		    data: 'zipcode='+zipcode,
		    dataType: 'xml',
		    error: function(){
		      //alert('Please try again or refresh the page to see if you are still logged in.');
		    },
		    success: function(xml){
		    	if($("error",xml).text()=='FALSE'){
	   				$("input[name="+fieldname_arr[1]+"]").val($("city",xml).text());
	   				$("select[name="+fieldname_arr[2]+"]").val($("state",xml).text());
	   			}
	   		}
		});
	}
}

function pageTimer(lastpage){
	if(typeof(ptimer)!='undefined'){
		clearTimeout(ptimer);
	}
	ptimer = setTimeout('pageDirect('+lastpage+')',1000);
}

function pageChange(pgmove,lastpage){
	var quantity = $("select#quantity").val();
	var curpage = parseInt($("input#pagebox").val());
	var newpage = Math.round(curpage + pgmove);
	if(newpage<=1){
		newpage=1;
	}else if(newpage>=lastpage){
		newpage=lastpage;
	}
	$("input#pagebox").val(newpage);
	var recstart = (newpage-1)*quantity;
	$("input#recstart").val(recstart);
	getLeads();
}

function pageDirect(lastpage){
	var curpage = parseInt($("input#pagebox").val());
	var quantity = $("select#quantity").val();
	if(curpage<=1){
		curpage=1;
	}else if(curpage>=lastpage){
		curpage=lastpage;
	}
	$("input#pagebox").val(curpage);
	var recstart = (curpage-1)*quantity;
	$("input#recstart").val(recstart);
	getLeads();
}

function rowSort(column){
	if(column=='date'){
		if($('#rowdir').val()=='' || $('#rowsort').val()!='quote_eventstarttime'){
			$('#datecol').html('Date &#9650;');
			$('#rowdir').val('ASC');
		}else if($('#rowdir').val()=='ASC'){
			$('#datecol').html('Date &#9660;');
			$('#rowdir').val('DESC');
		}else if($('#rowdir').val()=='DESC'){
			$('#datecol').html('Date');
			$('#rowdir').val('');
			$('#rowsort').val('');
		}
		$('#rowsort').val('quote_eventstarttime');
	}else if(column=='org'){
		if($('#rowdir').val()=='' || $('#rowsort').val()!='quote_eventorganization'){
			$('#orgcol').html('Organization &#9650;');
			$('#rowdir').val('ASC');
		}else if($('#rowdir').val()=='ASC'){
			$('#orgcol').html('Organization &#9660;');
			$('#rowdir').val('DESC');
		}else if($('#rowdir').val()=='DESC'){
			$('#orgcol').html('Organization');
			$('#rowdir').val('');
			$('#rowsort').val('');
		}
		$('#rowsort').val('quote_eventorganization');
	}else if(column=='status'){
		if($('#rowdir').val()=='' || $('#rowsort').val()!='quote_status'){
			$('#statuscol').html('Status &#9650;');
			$('#rowdir').val('ASC');
		}else if($('#rowdir').val()=='ASC'){
			$('#statuscol').html('Status &#9660;');
			$('#rowdir').val('DESC');
		}else if($('#rowdir').val()=='DESC'){
			$('#statuscol').html('Status');
			$('#rowdir').val('');
			$('#rowsort').val('');
		}
		$('#rowsort').val('quote_status');
	}else if(column=='last'){
		if($('#rowdir').val()=='' || $('#rowsort').val()!='contact_lastname'){
			$('#lastcol').html('Last Name &#9650;');
			$('#rowdir').val('ASC');
		}else if($('#rowdir').val()=='ASC'){
			$('#lastcol').html('Last Name &#9660;');
			$('#rowdir').val('DESC');
		}else if($('#rowdir').val()=='DESC'){
			$('#lastcol').html('Last Name');
			$('#rowdir').val('');
			$('#rowsort').val('');
		}
		$('#rowsort').val('contact_lastname');
	}else if(column=='total'){
		if($('#rowdir').val()=='' || $('#rowsort').val()!='quote_total'){
			$('#totalcol').html('Total &#9650;');
			$('#rowdir').val('ASC');
		}else if($('#rowdir').val()=='ASC'){
			$('#totalcol').html('Total &#9660;');
			$('#rowdir').val('DESC');
		}else if($('#rowdir').val()=='DESC'){
			$('#totalcol').html('Total');
			$('#rowdir').val('');
			$('#rowsort').val('');
		}
		$('#rowsort').val('quote_total');
	}
	getLeads();
}

function getLeads(){
 	//alert('getLeads');
 	//to go to a lead directly or not
 	var leadid = $("input#leadid").val();
 	var reqlid = $("input#reqlid").val();
 	if(reqlid=='none'){
 		leadid='none';
		closeLead();
 	}else{
 		leadid=reqlid;
 		$("input#reqlid").val('none');
 	}
 	//to start a new lead and load a customer's info
 	var cid = $("input[name=cid]").val();
 	$("input[name=cid]").val('');
 	if(cid){
 		leadid=0;
 	}
	var vpreset = $("select#preset").val();
	var vorganization = encodeURIComponent($("#organization").val());
	var vstatus = ''; 
	$("input[name='status[]']").each(function(){ 
		if(this.checked){ 
			vstatus += "&status[]=" + this.value; 
		} 
	});
	var vname = $("a#name").text();
	var vdate = $("input#date").val();
	var vkeyword = $("input#keyword").val();
	var vquantity = $("select#quantity").val();
	var vrecstart = $("input#recstart").val();
	var vrowsort = $("input#rowsort").val();
	var vrowdir = $("input#rowdir").val();
	var selected_rentals = $("input[name=selected_rentals]").val();
	var selected_locations = $("input[name=selected_locations]").val();
	var selected_salesrep = $("input[name=selected_salesrep]").val();
  $('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
			async: false,
	    url: '../include/getleads.php',
	    type: 'POST',
	    data: 'preset='+vpreset+'&organization='+vorganization+vstatus+'&name='+vname+'&date='+vdate+'&keyword='+vkeyword+'&quantity='+vquantity+'&recstart='+vrecstart+'&rowsort='+vrowsort+'&rowdir='+vrowdir+'&selected_rentals='+selected_rentals+'&selected_locations='+selected_locations+'&selected_salesrep='+selected_salesrep,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
  			$('#pagecontent').unblock();
	    },
	    success: function(txt){
	    	if(txt!='Error: Code exists!'){
   				$("#recordContainer").replaceWith(txt);
					$("#recordlist").scrollableFixedHeaderTable(795,498);
   				var newrecstart = ($("input#pagebox").val()-1)*$("select#quantity").val();
   				$("input#recstart").val(newrecstart);
   				//clear checkboxes
					$("input[name='leadsel[]']:checked").each(function(){
						$(this).removeAttr('checked');
					});
    			//scroll to lead code
					$('div.sfhtData > table > tbody > tr').click(function(e){
							var position = $(this).position();
							var headerheight = $('.header').height();
							var rowheight = $(this).height();
    					var currentpos = $('.sfhtData').scrollTop();
							var scrollhere = position.top + currentpos - rowheight - headerheight;
							//alert("headerheight="+headerheight+" rowheight="+rowheight+" currentpos="+currentpos+" position="+position.top);
				    	rowCount();
							$('.sfhtData').scrollTop(scrollhere);
   				});
					if(leadid!=0 && leadid!='none' && $('#row_'+leadid).length>0){ //leadid is set and it is present in the leads table
						//alert(leadid);
						$('#row_'+leadid).click();
						//var headersize = $('.tableContainer table>thead').height();
						/*var headersize=0;
						var rowloc = $('#row_'+leadid).offset().top;
						var tableloc = $('.sfhtData').offset().top;
						//alert(rowloc+'  '+tableloc+' '+headersize);
						if(rowloc-tableloc-130>=0){
								$('.sfhtData').scrollTop(rowloc-tableloc-headersize);
						}*/
					}else if(leadid==0){ //making a new lead
						$("input#leadid").val(0);
				    rowCount();
						editTab(cid);
					}else if(leadid!=0 && leadid!='none' && $('#row_'+leadid).length==0){
						cancelEdit();
						closeLead();
						rowCount();
   					//alert('here');
					}else{
						rowCount();
					}
   			}else{
    			$(".recordContainer").html(txt);
	    	}
  			$("input#recstart").val(vrecstart);
  			$('#pagecontent').unblock();
   			$.unblockUI();
 		}
	});
}

function openLead(id){
	//alert('openLead');
  //clear checkboxes
  $('input[name="leadsel[]"]:checked').each(function(){
	//$("input[name='leadsel[]']:checked").each(function(){
		$(this).removeAttr('checked');
	});
	//$("div#llcontainer").animate({height: "130px",overflow: scroll});
 	var gototab = $("input#gototab").val();
	if(!gototab || gototab==="" || id==0){
		gototab=1;
	}
	if($("input#saveprompt").val()==1){
		var answer = confirm('Save changes?');
		if(answer){
			//save changes here
			saveTab(id);
		}else{
			$("#output1").empty();
			showLead(id,'edit',gototab);
			if(id!=0){
				$("div#canceledit").css("display","none");
			}
		}
	}else{
		showLead(id,'edit',gototab);
	}
	//alert($("div#tabs").attr("display"));
	//if(typeof $("div#tabs").attr("display")!='undefined'){
	//	for(i=1; i<=3; i++){
	//		$("#tabs > ul").tabsEnable(i);
	//	}
	//}
}

function resetFilter(){
	closeLead();
 	$("select#preset").val('none');
 	$("#organization").val('');
	$("input[type='checkbox'][name='status[]']").attr('checked',true);
 	$("input#date").val('');
 	$("input#keyword").val('');
 	$("select#quantity").val('30');
	$("input#pagebox").val('1');
	$("input#recstart").val('0');
	$("input[name=selected_rentals]").val('');
	$("input[name=selected_locations]").val('');
	$("input[name=selected_salesrep]").val('');
	$("#show_filters").empty();
 	leadTimer();
}

function closeLead(){
 	var leadid = $("input#leadid").val();
	if($("input#saveprompt").val()==1){
		var answer = confirm('Save changes?');
		if(answer){
			//save changes here
			saveTab(leadid);
			$("input#reqlid").val('none');
		}else{
			$("input#saveprompt").val(0);
			$("#output1").empty();
			$("table#leadheader").hide();
			$("#leadControls").hide();
			$("div#edittab").hide();
			$("div#tabs").hide();
			$("div#canceledit").hide();
			$('#row_'+leadid).removeClass("rowSelected");
		}
	}else{
		$("table#leadheader").hide();
		$("#leadControls").hide();
		$("div#edittab").hide();
		$("div#tabs").hide();
		$("div#canceledit").hide();
		$('#row_'+leadid).removeClass("rowSelected");
	}
	$("input#leadid").val("");
	$("input#reqlid").val('none');
	rowCount();
}

function cancelBubble(evt){
	evt.cancelBubble=true;
}

function updateDate(){
	var daterange = $('input#date').val();
	if(daterange.length==0 || daterange.indexOf('-')!=-1){
		$("input#leadid").val(0);
		getLeads();
	}
}

function delLeads(){
	var answer = confirm('Delete lead(s)?');
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	if(answer){
 		var leadid = $("input#leadid").val();
 		var numselected = 0;
 		$("input#reqlid").val(leadid);
		$('#dowhat').val('deleteleads');
		$('input[name="leadsel[]"]:checked').each(function(){
			if($(this).val()==leadid){
				$("input#reqlid").val('none');
			}
			numselected++;
		});
		if(numselected>0){
			if(leadid=='' | leadid=='none'){
				$("input#reqlid").val('none');
			}
			$('#frmleadslist').submit();
		}else{
  		$.unblockUI();
			alert('No Leads Selected!');
		}
	}
}

function groupLeads(){
	var answer = confirm('Group lead(s)?');
	if(answer){
		$('#dowhat').val('groupleads');
		$('#frmleadslist').submit();
	}
}

function newLead(){
	$("#tabs > ul").tabsClick(1); //this selects the event tab, which is where we want to be for a new lead
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
  //resetFilter();
  //could not use resetFilter function because of asynchronous behavior, openlead was finishing first causing a save prompt popup
  closeLead();
	openLead(0);
}

function updateStatus(status){
	var curstatus = $('.img_current').attr("title");
	var leadid = $("input#leadid").val();
	if(status!=curstatus && leadid!=0){
		if($("input#saveprompt").val()==1){
			var answer = confirm('Save changes?');
			if(answer){
				//save changes here
				saveTab(leadid);
			}
		}
		$("input#saveprompt").val(0);
		
		//if(curstatus=='Quote' && status!='Quote'){
		//	var setupduration = $("#setdur").html();
		//	var tdownduration = $("#tddur").html();
		//	var ttimefrom = $("#ttfrom").html();
		//	if((setupduration==0 || setupduration=="" || setupduration!=parseFloat(setupduration)) || (tdownduration==0 || tdownduration=="" || tdownduration!=parseFloat(tdownduration)) || (ttimefrom==0 || ttimefrom=="" || ttimefrom!=parseFloat(ttimefrom))){
		//		alert('To upgrade from Quote status you must fill in setup, tear down, and travel time estimates on the Contract tab!');
		//	}else{
  	//		$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
		//		$.ajax({
		//		    url: '../include/leadmods.php',
		//		    type: 'POST',
		//		    data: 'dowhat=changestatus&leadid='+leadid+'&status='+status,
		//		    dataType: 'xml',
		//		    error: function(){
		//		    	$.unblockUI();
		//		      //alert('Please try again or refresh the page to see if you are still logged in.');
		//		    },
		//		    success: function(xml){
		//		    	if($("error",xml).text()=='FALSE'){
		//						$('#row_'+$("leadid",xml).text()).replaceWith($("tablerow",xml).text());
  	//		  			openLead($("leadid",xml).text());
  	//		 			}else{
  	//		  			$(".tableContainer").before($("errorhtml",xml).text());
		//		    	}
  	//					$.unblockUI();
		//		    }
		//		});
		//	}
		//}else{
  		$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
			$.ajax({
			    url: '../include/leadmods.php',
			    type: 'POST',
			    data: 'dowhat=changestatus&leadid='+leadid+'&status='+status,
			    dataType: 'xml',
			    error: function(){
  					$.unblockUI();
			      //alert('Please try again or refresh the page to see if you are still logged in.');
			    },
			    success: function(xml){
			    	if($("error",xml).text()=='FALSE'){
							$('#row_'+$("leadid",xml).text()).replaceWith($("tablerow",xml).text());
							closeLead();
  		  			openLead($("leadid",xml).text());
  		 			}else{
  		  			$(".tableContainer").before($("errorhtml",xml).text());
			    	}
  					$.unblockUI();
			    }
			});
		//}
	}
}

function showLead(leadid,action,tab){
	//alert('showLead');
	//set color of row if selected and return color if not selected
	var pastleadid = $("#leadid").val();
	$("tr#row_"+pastleadid).removeClass("rowSelected");
	$("tr#row_"+leadid).addClass("rowSelected");
	//ajax call to load selected lead info
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/showlead.php',
			//async: false,
	    type: 'GET',
	    data: 'leadid='+leadid+'&action='+action+'&tab='+tab,
	    dataType: 'xml',
	    //timeout: 3000,
	    error: function(){
			  	$.unblockUI();
	        //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
   			$("div#event").html($("event",xml).text());
   			$("div#contract").html($("contract",xml).text());
   			$("div#schedule").html($("schedule",xml).text());
   			$("div#surveys").html($("surveys",xml).text());
   			$("div#emails").html($("emails",xml).text());
   			$("#eventheading").html($("eventheading",xml).text());
   			$("#statusrow").html($("statusrow",xml).text());
				$("tr#row_"+leadid).css("font-style","normal");
				if(leadid!=0){
					for(i=1; i<=5; i++){
						$("#tabs > ul").tabsEnable(i);
					}
					$("#tabs > ul").tabsClick($("input#gototab").val());
			  	$.unblockUI();
			  }
				$('a#alert').cluetip({ width: '250', height: '100', arrows: true, dropShadow: false, hoverIntent: false, showTitle: false, cluetipClass: 'jtip',
  				sticky: true, mouseOutClose: false, cursor: 'pointer', closePosition: 'title', ajaxCache: false, closeText: 'close'
				});
				$('.popcon').cluetip({ width: '550', height: '200', arrows: true, dropShadow: false, showTitle: false, cluetipClass: 'jtip',
  				sticky: true, mouseOutClose: true, cursor: 'pointer', closePosition: 'title', ajaxCache: false, closeText: 'close'
				});
				$('#leadid').val(leadid);
				if(leadid!=0){
					$("table#leadheader").show();
					$("#leadControls").show();
					$("div#edittab").css("display","block");
					$("div#tabs").css("display","block");
					$('#savecopy').show();
				}else{
					$('#savecopy').hide();
					editTab(0);
				}
				//if($.browser.msie){
					//$(".ui-tabs-nav").css("padding-bottom","18px");
				//						
			//	}else{
					
					//$(".tableContainer").css("height","178px");
				//}
				rowCount();
				window.location.href = "#leadview"; 
		    img1 = new Image();
		    img1.src = "../images/wait_line.gif";
	    }
	});
}

function editTab(cid){
	//alert('editTab');
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
  var leadid = parseInt($("input#leadid").val());
  //if(typeof leadid=='undefined'){
	//	var leadid = $("input#leadid").val();
	//}
	var page = '';
	if(leadid==0){
		$("#tabs > ul").tabsClick(1);
	}
	//test for tab element, set currenttab to 1 if it doesn't exist
	var currenttab = $("#tabs > ul").tabsSelected();
	if(currenttab==1){
		page = '../include/editevent.php';
	}else if(currenttab==2){
		page = '../include/editcontract.php';
	}else if(currenttab==3){
		page = '../include/editschedule.php';
	} 
	for(i=1; i<=5; i++){
		if(i!=currenttab){
			$("#tabs > ul").tabsDisable(i);
		}
	}
	$.ajax({
	    url: page,
			async: false,
	    type: 'GET',
	    data: 'leadid='+leadid+'&cid='+cid,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
				$.unblockUI();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(html){
				if(currenttab==1){
   				$("div#event").html(html);
				}else if(currenttab==2){
   				$("div#contract").html(html);
				}else if(currenttab==3){
   				$("div#schedule").html(html);
				}
				tabLoaded();
				$('.popcon').cluetip({ width: '550', height: '200', arrows: true, dropShadow: false, showTitle: false, cluetipClass: 'jtip',
  				sticky: true, mouseOutClose: true, cursor: 'pointer', closePosition: 'title', ajaxCache: false, closeText: 'close'
				});
				$.unblockUI();
	    }
	});
	$("table#leadheader").show();
	$("#leadControls").show();
	$("div#tabs").css("display","block");
	$("div#edittab").css("display","none");
	$("div#canceledit").css("display","block");
	if(currenttab==1 && leadid!=0){
		$('#savecopy').show();
	}else{
		$('#savecopy').hide();
	}
}

function saveTab(action){
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	var currenttab = $("#tabs > ul").tabsSelected();
	if(currenttab==1){
		$('#dowhat_tabs').val('saveeventtab');
	}else if(currenttab==2){
		$('#dowhat_tabs').val('savecontrtab');
		if($('.htmlarea').length!=0){
			var editor = xinha_editors.text;
			var html = editor.outwardHtml(editor.getHTML());
			$("textarea[name='text']").val(html);
		}
	}else if(currenttab==3){
		$('#dowhat_tabs').val('saveschedtab');
	}
	if(action=='copy'){
		$('#dowhat_tabs').val($('#dowhat_tabs').val()+'_copy');
		$("input#reqlid").val('copy');
	}else if(action==parseInt(action) || action==0){
		$("input#reqlid").val(action);
		//alert($("input#reqlid").val());
	}else{
		$("input#reqlid").val($("input#leadid").val());
	}
	$('#frmlead').submit();
}

function updateEventtab(){
	//this updates the event tab while you are editting it, without saving the info to the database
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	var currenttab = $("#tabs > ul").tabsSelected();
	$('#dowhat_tabs').val('updateeventtab');
	$("input#reqlid").val($("input#leadid").val());
	$('#frmlead').submit();
}

function leadSaved(xml){
	//alert('leadSavedstart');
  var html_out = $("html_out",xml).text();
  if($("error",xml).text()=='true'){
  	$("#output1").empty();
  	$('#output1').append('<br/><span style="padding-left:1em;">Errors:</span>'+$("errorhtml",xml).text());
  	window.scroll(0,0);
  	//cancelEdit(); allows user to correct errors
  }else if(html_out.length!=0){ //case where user chooses update
  	$("#output1").empty();
  	$("div#event").html(html_out);
		tabLoaded();
	}else{
  	$("#output1").empty();
  	$("input#saveprompt").val(0);
  	var leadid = $("leadid",xml).text();
		//$('#row_'+leadid).replaceWith($("tablerow",xml).text());
		var currenttab = $("#tabs > ul").tabsSelected();
		for(i=1; i<=5; i++){
			if(i!=currenttab){
				$("#tabs > ul").tabsEnable(i);
			}
		}
		$("div#edittab").css("display","block");
		$("div#canceledit").css("display","none");
		if($("input#reqlid").val()=='copy' || $("input#reqlid").val()==0){ //set new id for copied or new lead
			$("input#leadid").val(leadid);
			$("input#reqlid").val(leadid);
			//tlb removed 12/7/2010 because reqlid set below is used in getleads to do the same, we were doing it twice.
			/*if(leadid>0){
				window.location.href =  './directlead.php?id=' + encodeURIComponent(leadid);
			}*/
		}
		closeLead();
		$("input#reqlid").val(leadid);
		getLeads();
  	//showLead(leadid,'edit','1');
  }
	$.unblockUI();
	//alert('leadSavedend');
}

function cancelEdit(){
	//alert('cancelEdit');
	var currenttab = $("#tabs > ul").tabsSelected();
	var leadid = $("input#leadid").val();
	if(leadid!=0){
  	$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
		var page = '../include/showlead.php';
		for(i=1; i<=5; i++){
			if(i!=currenttab){
				$("#tabs > ul").tabsEnable(i);
			}
		}
		$.ajax({
		    url: page,
		    type: 'GET',
		    data: 'leadid='+leadid+'&action=cancel&tab='+currenttab,
		    dataType: 'html',
		    //timeout: 3000,
		    error: function(){
					$.unblockUI();
		      //alert('Please try again or refresh the page to see if you are still logged in.');
		    },
		    success: function(html){
					if(currenttab==1){
  	 				$("div#event").html(html);
					}else if(currenttab==2){
  	 				$("div#contract").html(html);
					}else if(currenttab==3){
  	 				$("div#schedule").html(html);
					}
					$('.popcon').cluetip({ width: '550', height: '200', arrows: true, dropShadow: false, showTitle: false, cluetipClass: 'jtip',
  					sticky: true, mouseOutClose: true, cursor: 'pointer', closePosition: 'title', ajaxCache: false, closeText: 'close'
					});
					$.unblockUI();
		    }
		});
		$("div#edittab").css("display","block");
		$("div#canceledit").css("display","none");
		$("#output1").empty();
	}else{
		for(i=1; i<=5; i++){
			if(i!=currenttab){
				$("#tabs > ul").tabsEnable(i);
			}
		}
		$("div#edittab").css("display","block");
		$("div#canceledit").css("display","none");
		$("input#reqlid").val('none');
		//$("input#leadid").val('none');
  	$("input#saveprompt").val(0);
		$("#output1").empty();
		getLeads();
		$("div#tabs").hide();
		$("table#leadheader").hide();
		$("#leadControls").hide();
	}
}

function load_cat(cats,cat_index,leadid,orig_updatetime){
			var cat_id=cats[cat_index];
			var cat_id_arr=cat_id.split('_');
			var cat_id_only=cat_id_arr[1];
			var eventstarttime = $("#eventstarttime").val();
			var eventduration = $("#eventduration").val();
			var fillcat_updatetime = $("input[name=fillcat_updatetime]").val();
			var selectedrides = $('input[name=rentals\\[\\]]:checked').serialize();
			
			var img_id=cat_id.replace('cat','img');
			if($('#'+img_id).length > 0){
				$.ajax({
				    url: '../include/fillcategories.php',
				    type: 'POST',
				    data: 'leadid='+leadid+'&catid='+cat_id_only+'&eventstarttime='+eventstarttime+'&eventduration='+eventduration+'&'+selectedrides,
				    dataType: 'html',
				    //timeout: 3000,
				    error: function(){
			  			$('#pagecontent').unblock();
				      //alert('fillcat error. Please try again or refresh the page to see if you are still logged in.');
				    },
				    success: function(txt){
				    	if(txt!='Error: Code exists!'){
			    			$('#'+cat_id).after(txt);
								$('#'+img_id).remove();
			   			}
			   			if(cat_index<cats.length-1){
			   				cat_index++;
			   				if($("input#saveprompt").val()==1 && $("#update").length > 0){// && fillcat_updatetime==orig_updatetime){
			   					load_cat(cats,cat_index,leadid,orig_updatetime);
			   				}
			   			}
			  		}
				});
			}
}

		
function tabLoaded(){
	if($('.dpbutton')){
		$('.dpbutton').datepicker({dateFormat: 'm/d/yy', speed: 'fast', 
  		showOn: 'both', buttonImage: '../images/calendar.gif', buttonImageOnly: true,	buttonText: 'Calendar'});
  }
	if($("#tabs > ul").tabsSelected()==1){
		
		$( "#name" ).autocomplete({
			source: "../include/cust_search.php",
			minLength: 2,
			select: function( event, ui ) {
				$('input#eventorganization').val(ui.item.eventorganization);
				$('input#street').val(ui.item.street);
				$('input#city').val(ui.item.city);
				$('input#state').val(ui.item.state);
				$('select[name=state] option[value='+ui.item.state+']').attr('selected', 'selected');
				$('input#zip').val(ui.item.zip);
				$('input#officephone').val(ui.item.officephone);
				$('input#homephone').val(ui.item.homephone);
				$('input#cellphone').val(ui.item.cellphone);
				$('input#fax').val(ui.item.fax);
				$('input#email').val(ui.item.email);
				$('textarea#notes').val(ui.item.notes);
				if(ui.item.exempt=='Yes'){
					$("input[name='taxexempt']").attr("checked",true);
					checkTexempt();
					$("#xmptlink").text('(exempt)    ');
					if($("#xmptlink").length>0){
						load_jsonp_certs_custid(ui.item.id)
					}
				}else{
					$("input[name='taxexempt']").attr("checked",false);
					//checkTexempt();
					$("#xmptlink").text('(Exempt?)    ');
					if($("#xmptlink").length>0){
						load_jsonp_certs_custid(ui.item.id)				
					}
				}
				
			}
		});
		
		//to load items into categories for big customers
		var leadid=$('input#leadid').val();
		var cat_index=0;
		var cats= new Array();
		$('.category_name').each(function(){
			cats[cat_index] = $(this).attr('id');
			cat_index++;
		});
		
		if(cat_index>0){
			var fillcat_updatetime = $("input[name=fillcat_updatetime]").val();
			load_cat(cats,0,leadid,fillcat_updatetime);
		}
		
		//clear ridequote when quantity is changed
		$("select[name=\'rentalqty[]\']").change(function(){
			var ridequotes_id=$(this).attr("id").replace("qty","ridequotes");
			$("#"+ridequotes_id).val("");
		});
		//category stuff
		$(".category_name").click(function(){
			var id_arr = $(this).attr("id").split("_");
			$(".cat_"+id_arr[1]).toggle();
			$(".cat_items").each(function(){
				if($(this).attr("class").search("cat_items cat_"+id_arr[1])==-1){
				//if($(this).attr("class")!="cat_items cat_"+id_arr[1]){
					$(this).hide();
				}
			});
		});
		$(".category_name").css("cursor", "pointer");
		$(".category_name").hover( function(){
			  $(this).css("color", "#6D949B");
			},
			function(){
			  $(this).css("color", "#000000");
		});
		
		//if($("#xmptlink").length>0){
			//var clearUrl = "?time="+new Date().getTime().toString(); // prevent caching
			var clearUrl = "";
			(function () {
			    var tcJsHost = (("https:" == document.location.protocol) ? "https:" : "http:"); var ts = document.createElement('script'); ts.type = 'text/javascript'; ts.async = true;
			    ts.src = '../javascript/taxcloud.cert.min.js' + clearUrl; var t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(ts, t);
			})();
		//}


		
	}
	if(($("#tabs > ul").tabsSelected()==1 | $("#tabs > ul").tabsSelected()==2)&& $(".time_picker")){
		//time stuff
		$(".time_picker").timePicker({
		  startTime: new Date(0, 0, 0, 0, 0, 0), // Using string. Can take string or Date object.
		  endTime: new Date(0, 0, 0, 23, 45, 0), // Using Date object here.
		  show24Hours: false,
		  separator: ":",
		  step: 15
		});
	  //these set the end window time the same as the start times if empty
		$("input[name=startdate]").change(function() {
		  if( $("input[name=enddate]").val()=='' ||  new Date($("input[name=enddate]").val()) < new Date($("input[name=startdate]").val())){
				$("input[name=enddate]").val($("input[name=startdate]").val());
			}
		});
		$("input[name=starttime]").change(function() {
		  if( $("input[name=endtime]").val()==''){
				$("input[name=endtime]").val($("input[name=starttime]").val());
			}
		});
		//these update the times for each rental when the main event times and dates are changed
		$(".dpbutton").change(function(){
			//updateTimes();
		});
		$(".time_picker").change(function(){
			//updateTimes();
		});
	  
	  
		$("input[name=dropoff_window_start]").change(function() {
		  if( $("input[name=dropoff_window_end]").val()==''  ||  new Date($("input[name=dropoff_window_end]").val()) < new Date($("input[name=dropoff_window_start]").val())){
				$("input[name=dropoff_window_end]").val($("input[name=dropoff_window_start]").val());
			}
		});
		$("input[name=dropoff_window_start_time]").change(function() {
		  if( $("input[name=dropoff_window_end_time]").val()=='' ){
				$("input[name=dropoff_window_end_time]").val($("input[name=dropoff_window_start_time]").val());
			}
		});
		$("input[name=pickup_window_start]").change(function() {
		  if( $("input[name=pickup_window_end]").val()==''   ||  new Date($("input[name=pickup_window_end]").val()) < new Date($("input[name=pickup_window_start]").val())){
				$("input[name=pickup_window_end]").val($("input[name=pickup_window_start]").val());
			}
		});
		$("input[name=pickup_window_start_time]").change(function() {
		  if( $("input[name=pickup_window_end_time]").val()=='' ){
				$("input[name=pickup_window_end_time]").val($("input[name=pickup_window_start_time]").val());
			}
		});
		//$("input[name=dropoff_window_start_time]").change(function() {
		//	var thistime = $.timePicker(this).getTime();
		//	var othertime = $.timePicker("input[name=dropoff_window_end_time]").getTime();
		//  if( othertime==null ){
		//		$.timePicker("input[name=dropoff_window_end_time]").setTime(new Date(new Date(thistime.getTime())));
		//	}
		//});
	}
	if($("#tabs > ul").tabsSelected()==2 && $('#ctrtemprow').is(":visible")){
		//initialize xinha editor
		$.getScript("../xinha/xinha_custom.js", function(){
		   // here you can use anything you defined in the loaded script
		   xinha_init();
		});
  }
	$.unblockUI();
}

function printTab(){
	var currenttab = $("#tabs > ul").tabsSelected();
	//var page = '../include/showlead.php?leadid='+leadid+'&action=print&tab='+currenttab;
	var leadid=$('input#leadid').val();
	var contactid=$('input#contactid').val();
	var custcontractid=$('select[name=contract]').val();
	var ctemail=$('#ctemail').text();
	var page = '';
	var winprefs = '';
	if(leadid==0){
		$("#tabs > ul").tabsClick(1);
	}
	var currenttab = $("#tabs > ul").tabsSelected();
	var report_title='';
	if(currenttab==1){
		page = '../quotes/quote.php?quoteid='+leadid+'&contactid='+contactid+'&ctemail='+ctemail;
		winprefs = '';
		//winprefs = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=750,height=720';
		//page = '../include/editevent.php';
	}else if(currenttab==2){
		page = '../quotes/contract.php?leadid='+leadid+'&contactid='+contactid+'&custcontractid='+custcontractid;
		winprefs = '';
		//winprefs = 'menubar=1,toolbar=1,scrollbars=1,width=875';
		//page = '../include/editcontract.php';
	}else if(currenttab==3){
		page = "./viewreport.php?leadid="+leadid+"&contactid="+contactid+"&report=Packing Lists";  
		report_title="Report";
		winprefs = '';
	}else if(currenttab==4){
		page = '../include/showlead.php?action=print&leadid='+leadid+'&tab=4';
		winprefs = '';
		//winprefs = 'menubar=1,toolbar=1,scrollbars=1,width=875';
		//page = '../include/editschedule.php';
	}else if(currenttab==5){
		page = '../include/showlead.php?action=print&leadid='+leadid+'&tab=5';
		winprefs = '';
		//winprefs = 'menubar=1,toolbar=1,scrollbars=1,width=875';
		//page = '../include/editschedule.php';
	} 
	window.open(page,report_title,winprefs);
}

function emailTab(){
	var currenttab = $("#tabs > ul").tabsSelected();
	var leadid=$('input#leadid').val();
}

//disable & enable organization input box
//disable_inputbox(checkbox name, input box name)
function disable_inputbox(formfield, chgformfield)
{
  var curformfield = typeof chgformfield != 'undefined'? chgformfield : "";
	if(formfield.checked == true){
		chgformfield.disabled = true;
		//chgformfield.value = 'n/a';
	}else{
		chgformfield.disabled = false;
		//chgformfield.value = '';
	}
	return true;
}

/*function findPos(obj){
	var curleft = curtop = 0;
	if(obj.offsetParent){
		do{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}while(obj = obj.offsetParent);
		return [curleft,curtop];
	}
}*/

function addShift(){
	var leadid = $("input#leadid").val();
	var stafftosend = $("input#stafftosend").val();
	var setupduration = $("input[name='setupduration']").val();
	var tdownduration = $("input[name='tdownduration']").val();
	var ttimefrom = $("input#ttimefrom").val();
	var meetingloc = $("input[name='meetingloc_add']").val();
	var position = $("input[name='position_add']").val();
	var totalrows = $('div#schedule .settingsRow01').length;
  //$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
  $('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/addshifts.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&stafftosend='+stafftosend+'&setupduration='+setupduration+'&tdownduration='+tdownduration+'&ttimefrom='+ttimefrom+'&meetingloc='+meetingloc+'&position='+position+'&totalrows='+totalrows,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
  			$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(txt){
	    	if(txt!='Error: Code exists!'){
    			$("#addshifts").before(txt);
					$('.dpbutton').datepicker({dateFormat: 'm/d/y', speed: 'fast', 
			  		showOn: 'both', buttonImage: '../images/calendar.gif', buttonImageOnly: true,	buttonText: 'Calendar'});
   			}else{
    			$(".tableContainer").html(txt);
	    	}
  			//$.unblockUI();
  			$('#pagecontent').unblock();
  		}
	});
}

function delShift(rownum){
	if($("input[name='shiftstodel']").val()){
		$("input[name='shiftstodel']").val($("input[name='shiftstodel']").val()+','+$("tr#row_"+rownum+" input[name='shiftid[]']").val());
	}else{
		$("input[name='shiftstodel']").val($("tr#row_"+rownum+" input[name='shiftid[]']").val());
	}
	$('tr#row_'+rownum).remove();
}

function changePrices(tcon){
	var ridetotal=0;
	$('input[name="ridequotes[]"]').each(function(){
		if(!$(this).is(':disabled')){
			current_ridetotal=$(this).val().replace(/[\$\,\s]/g,'');
			if(current_ridetotal.search(/\*/g)!=-1){
				equation_arr=current_ridetotal.split("*");
				current_ridetotal=equation_arr[0]*equation_arr[1];
			}
			current_ridetotal=parseFloat(current_ridetotal);
			if(isNaN(current_ridetotal)==true){
				$(this).val('');
				current_ridetotal=0;
			}else{
				$(this).val(current_ridetotal);
			}
			ridetotal+=current_ridetotal;
		}
	});
	$('#ridetotal').text('$ '+Number(Math.round(ridetotal*100)/100).toFixed(2));
	changeDiscount(tcon);
	return true;
}

function changeDiscount(tcon){
	//var staff_tax=$('input[name=staff_taxable]').val();
	//var dist_tax=$('input[name=dist_taxable]').val();
	var discount = $('#adjust').val().replace(/[\$\,\s]/g,'');
	var ridetotal = $('#ridetotal').text().replace(/[\$\,\s]/g,'');
	var staffcost = $('#staffcost').val().replace(/[\$\,\s]/g,'');
	var distcharge = $('#distcharge').val().replace(/[\$\,\s]/g,'');
	var cpdiscount = $('#cpdiscount').text().replace(/[\$\,\s]/g,'');
	var spamount = $('input[name=spamount]').val();
	var fee = $('input[name=fee]').val().replace(/[\$\,\s]/g,'');
	var taxrate=0;
	var taxable_total = -Number(cpdiscount)-Number(spamount)+Number(fee);
	var non_taxable=0;
	if(isNaN(staffcost)==true){
		staffcost=mathCalc(staffcost,0);
	}
	if(isNaN(distcharge)==true){
		distcharge=mathCalc(distcharge,0);
	}
	if($("input[name='taxexempt']").attr("checked")!==true){
		taxrate = $('#taxrate').val();
	}
	$("input[name='rentals[]']").each(function(){
		if(this.checked){
			rtax_id = $(this).attr("id").replace('rental','rtax');
			ridequotes_id = $(this).attr("id").replace('rental','ridequotes');

			if(tcon==1){
				taxable_total+=Number($('#'+ridequotes_id).val().replace(/[\$\,\s]/g,''));
			}else{
				if($('#'+rtax_id).val()==1){
					taxable_total+=Number($('#'+ridequotes_id).val().replace(/[\$\,\s]/g,''));
				}else{
					non_taxable+=Number($('#'+ridequotes_id).val().replace(/[\$\,\s]/g,''));
				}
			}
		}
	});
	//if(dist_tax=='Yes'){
		taxable_total+=Number(distcharge);
	//}
	//if(staff_tax=='Yes'){
		taxable_total+=Number(staffcost);
	//}
	var subtotal = Number(ridetotal)+Number(staffcost)+Number(distcharge)-Number(cpdiscount)-Number(spamount)+Number(fee);
	if(isNaN(discount)==true){
		discount=mathCalc(discount,subtotal);
	}
	discount = Math.round(discount*100)/100;
	taxable_total-=discount;
	subtotal-=discount;
	var salestax = Math.round(taxable_total*taxrate)/100;
	if(salestax<0){salestax=0;}
	$('#adjust').val(Number(discount).toFixed(2));
	$('#staffcost').val(staffcost);
	$('#distcharge').val(distcharge);
	$('#showsalestax').text('$ '+salestax);
	$('#salestax').val(salestax);
	$('#total').val(Math.round((subtotal+salestax)*100)/100);
	//alert($('input#salestax').val());
	return true;
}

function mathCalc(equation,subtotal){
	var result;
	var multiply;
	if(equation.search(/\*/g)!=-1){
		equation_arr=equation.split("*");
		multiply=equation_arr[0];
		multiply = multiply.replace(/[\s%]/g,'');
		equation=equation_arr[1];
		equation = equation.replace(/[\s%]/g,'');
		if(isNaN(equation)==false){
			result = multiply*equation;
		}else{
			result = 0;
		}
	}else	if(equation.search(/[%]$/)!=-1){
		equation_arr=equation.split("%");
		multiply=equation_arr[0];
		equation=equation_arr[1];
		if(isNaN(equation)==false){
			result = subtotal*multiply/100;
		}else{
			result = 0;
		}
	}else{
		result = equation;
	}
	return result;
}

function changeTotal(tcon){
	//var staff_tax=$('input[name=staff_taxable]').val();
	//var dist_tax=$('input[name=dist_taxable]').val();
	var total = $('#total').val().replace(/[\$\,\s]/g,'');
	var taxrate = $('#taxrate').val();
	var ridetotal = $('#ridetotal').text().replace(/[\$\,\s]/g,'');
	var staffcost = $('#staffcost').val().replace(/[\$\,\s]/g,'');
	var distcharge = $('#distcharge').val().replace(/[\$\,\s]/g,'');
	var cpdiscount = $('#cpdiscount').text().replace(/[\$\,\s]/g,'');
	var spamount = $('input[name=spamount]').val();
	var fee = $('input[name=fee]').val().replace(/[\$\,\s]/g,'');
	var discount = $('#discount').val();
	var taxable_total = -Number(cpdiscount)-Number(spamount)+Number(fee);
	var non_taxable=0;
	$("input[name='rentals[]']").each(function(){
	if(this.checked){
		rtax_id = $(this).attr("id").replace('rental','rtax');
		ridequotes_id = $(this).attr("id").replace('rental','ridequotes');
		if(tcon==1){
			taxable_total+=Number($('#'+ridequotes_id).val().replace(/[\$\,\s]/g,''));
		}else{
			if($('#'+rtax_id).val()==1){
				taxable_total+=Number($('#'+ridequotes_id).val().replace(/[\$\,\s]/g,''));
			}else{
				non_taxable+=Number($('#'+ridequotes_id).val().replace(/[\$\,\s]/g,''));
			}
		}
	}
  });
	//if(dist_tax=='Yes'){
		taxable_total+=Number(distcharge);
	//}else{
	//	non_taxable+=Number(distcharge);
	//}
	//if(staff_tax=='Yes'){
		taxable_total+=Number(staffcost);
	//}else{
	//	non_taxable+=Number(staffcost);
	//}
	var subtotal = Number(ridetotal)+Number(staffcost)+Number(distcharge)-Number(cpdiscount)-Number(spamount)+Number(fee);
	var salestax = $('#showsalestax').text().replace(/[\$\,\s]/g,'');
	if(isNaN(total)==true){
		total=Number(subtotal)-Number(discount)+Number(salestax);
	}else{
		//discount = Math.round((-(total-Number(non_taxable))/(1+taxrate/100)+Number(ridetotal)-Number(spamount)-Number(cpdiscount))*100)/100;
		discount = Math.round(-((total-Number(taxable_total)-Number(non_taxable)-Number(taxable_total)*taxrate/100)/(taxrate/100+1))*100)/100;
		//salestax = Math.round(total*taxrate/100/(1+(taxrate/100))*100)/100;
		taxable_total-=Number(discount);
		salestax = Math.round((taxable_total*taxrate/100)*100)/100;
		if(salestax<0){salestax=0;}
		var new_total=Math.round((taxable_total+non_taxable+salestax)*100)/100;
	}
	//discount = Math.round((-total+Number(subtotal)+Number(salestax))*100)/100
	$('#adjust').val(discount);
	$('#showsalestax').text('$ '+salestax);
	$('#salestax').val(salestax);
	if(total!=new_total){
		$('#total').val(new_total);
	}else{
		$('#total').val(total);
	}
	//alert($('input#salestax').val());
	return true;
}

function directions_from(){
	var leadid = $("input#leadid").val();
	var lid = $("select[name=directionsfrom] option:selected").val();
	$.ajax({
	    url: '../include/loclookup.php',
	    type: 'GET',
	    data: 'leadid='+leadid+'&lid='+lid,
	    dataType: 'xml',
	    //timeout: 3000,
	    error: function(){
	        //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
	    	if($("error",xml).text()=='FALSE'){
	    		var startstr = $("startstr",xml).text();
	    		var eventstr = $("eventstr",xml).text();
					window.open('http://maps.yahoo.com/#mvt=m&q1='+startstr+'&q2='+eventstr);
   			}
  		}
	});
	return true;
}

function saveAlert(){
	var leadid = $("input#leadid").val();
	//alert($('#checkalert').attr('checked'));
	if($('#checkalert').attr('checked')===false){
		$.ajax({
		    url: '../include/savealert.php',
		    type: 'GET',
		    data: 'leadid='+leadid,
		    dataType: 'xml',
		    //timeout: 3000,
		    error: function(){
		        //alert('Please try again or refresh the page to see if you are still logged in.');
		    },
		    success: function(xml){
	    		if($("error",xml).text()=='FALSE'){
		    		$('#cluetip').hide();
   					$("#eventheading").html($("eventheading",xml).text());
   					$("#statusrow").html($("statusrow",xml).text());
						$('#row_'+leadid).replaceWith($("tablerow",xml).text());
						$("tr#row_"+leadid).addClass("rowSelected");
   				}
  			}
		});
	}else{
		$('#cluetip').hide();
	}
	return true;
}

function contempChg(){
	var leadid = $("input#leadid").val();
	var contracttemp = encodeURIComponent($("select[name=contracttemp]").val());
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	if(contracttemp.length>0){
		$.ajax({
		    url: '../include/getcontract.php',
				async: false,
		    type: 'GET',
		    data: 'leadid='+leadid+'&contracttemp='+contracttemp+'&fill=1',
		    dataType: 'xml',
		    //timeout: 3000,
		    error: function(){
					$.unblockUI();
		      //alert('Please try again or refresh the page to see if you are still logged in.');
		    },
		    success: function(xml){
		  		if($("error",xml).text()=='FALSE'){
	  				xinha_editors.text.setHTML($("text",xml).text());
  				}
  			}
		});
	}else{
		xinha_editors.text.setHTML('');
	}
	$.unblockUI();
}

function toggleCtrtemp(){
	$('#ctrtemprow').toggle();
	if($('#ctrtemprow').is(":visible") && $('.htmlarea').length==0){
		tabLoaded();
	}
}

function checkallRentals(tcon){
	if($("input[name='checkallrentals']").attr("checked")===true){
		$("input[name='rentals[]']").attr('checked',true);
		$("input[name='rentals[]']").each(function(){
			var rental_id=$(this).attr('id');
			var qty_id=rental_id.replace('rental','qty');
			changeStatus(qty_id,tcon);
		});
	}else{
		$("input[name='rentals[]']").attr('checked',false);
		$("input[name='rentals[]']").each(function(){
			var rental_id=$(this).attr('id');
			var qty_id=rental_id.replace('rental','qty');
			changeStatus(qty_id,tcon);
		});
	}
}

function checkTexempt(){
	if($("input[name='taxexempt']").attr("checked")===true){
		$("input[name='taxrate']").attr('disabled','disabled');
		$("input[name='taxrate']").val('');
		$('#showsalestax').text('$ 0.00');
		changeDiscount();
	}else{
		$("input[name='taxrate']").removeAttr('disabled');
		changeDiscount();
	}
}

/* superseded by new update button
function updateAvail(){
	var leadid = $("input#leadid").val();
	var startdate = $("input[name='startdate']").val();
	var starthour = $("select[name='starthour']").val();
	var startminute = $("select[name='startminute']").val();
	var startampm = $("select[name='startampm']").val();
	var endhour = $("select[name='endhour']").val();
	var endminute = $("select[name='endminute']").val();
	var endampm = $("select[name='endampm']").val();
	var query_string = ''; 
	var qty_id = ''; 
	$("input[name='rentals[]']").each(function(){
    if(this.checked){
      query_string += "&rentals[]=" + this.value;
      qty_id = $(this).attr("id").replace('rental','qty');
    	query_string += "&rentalqty[]=" + encodeURIComponent($('#'+qty_id).val());
      ridequotes_id = $(this).attr("id").replace('rental','ridequotes');
    	query_string += "&ridequotes[]=" + encodeURIComponent($('#'+ridequotes_id).val());
      hold_id = $(this).attr("id").replace('rental','hold');
    	query_string += "&rentalholdtime[]=" + encodeURIComponent($('#'+hold_id).val());
    }
  });
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/updateavail.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&startdate='+startdate+'&starthour='+starthour+'&startminute='+startminute+
	    			'&startampm='+startampm+'&endhour='+endhour+'&endminute='+endminute+'&endampm='+endampm+
	    			query_string,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
				$.unblockUI();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(txt){
	  		if(txt!='Error exists!'){
  				$("#rentallist").html(txt);
  				changePrices();
  				//if($("input[name='recalculate']").attr('checked')==0){
  				//	$("input[name='recalculate']").click();
  				//}
					$('.popcon').cluetip({ width: '550', height: '200', arrows: true, dropShadow: false, showTitle: false, cluetipClass: 'jtip',
  					sticky: true, mouseOutClose: true, cursor: 'pointer', closePosition: 'title', ajaxCache: false, closeText: 'close'
					});
					//category stuff
					$(".category_name").click(function(){
						var id_arr = $(this).attr("id").split("_");
						$(".cat_"+id_arr[1]).toggle();
						$(".cat_items").each(function(){
							if($(this).attr("class")!="cat_items cat_"+id_arr[1]){
								$(this).hide();
							}
						});
					});
					$(".category_name").css("cursor", "pointer");
					$(".category_name").hover( function(){
						  $(this).css("color", "#6D949B");
						},
						function(){
						  $(this).css("color", "#000000");
					});
  			}else{
  				$("#output1").html(txt);
	  		}
				$.unblockUI();
  		}
	});
}*/

function changeStatus(qid,tcon){
	var rental_id=qid.replace('qty','rental');
	var ridequotes_id=qid.replace('qty','ridequotes');
	var rtaxable_id=qid.replace('qty','rtax');
	var rentalholdtime_id=qid.replace('qty','hold');
	var rentalstarttime_id=qid.replace('qty','rentalstarttime');
	var rentalendtime_id=qid.replace('qty','rentalendtime');
	id=qid.substr(4);
	if($('#'+rental_id).is(':checked')){
		if($("input[name='recalculate']").attr("checked")===false){
			$('#'+ridequotes_id).removeAttr('disabled');
		}
		$('#'+qid).removeAttr('disabled');
		$('#'+rtaxable_id).removeAttr('disabled');
		$('#'+rentalholdtime_id).removeAttr('disabled');
		$('#'+rentalstarttime_id).removeAttr('disabled');
		$('#'+rentalendtime_id).removeAttr('disabled');
		$('.tr_'+id).show();//show/hide options for rental
		$('.tr_'+id+' input[type=checkbox]').each(function(){
			var option_qty_id=$(this).attr('id').replace('rental','qty');
			var option_ridequotes_id=$(this).attr('id').replace('rental','ridequotes');
			var option_required_id=$(this).attr('id').replace('rental','option_required');
			if($('#'+option_required_id).val()==1){
				$(this).attr('checked','checked');
				$('#'+option_qty_id).removeAttr('disabled');
				if($('input[name=recalculate]:checked').length=='undefined'){
					$('#'+option_ridequotes_id).removeAttr('disabled');
				}
			}
			//alert($(this).attr('id'));
			if($(this).attr('checked')=='checked'){
				$('#'+option_qty_id).removeAttr('disabled');
				$('#'+option_ridequotes_id).removeAttr('disabled');
			}
		});
	}else{
		$('#'+qid).attr('disabled',true);
		$('#'+ridequotes_id).attr('disabled',true);
		$('#'+rtaxable_id).attr('disabled',true);
		$('#'+rentalholdtime_id).attr('disabled',true);
		$('#'+rentalstarttime_id).attr('disabled',true);
		$('#'+rentalendtime_id).attr('disabled',true);
		$('.tr_'+id+' input[type=checkbox]').each(function(){
			var option_ridequotes_id=$(this).attr('id').replace('rental','ridequotes');
			$(this).removeAttr('checked');
			if($('input[name=recalculate]:checked').length=='undefined'){
				$('#'+option_ridequotes_id).attr('disabled',true);
			}
		});
		$('.optqty_'+id).attr('disabled',true);
		$('.tr_'+id).hide();//show/hide options for rental
	}
	changePrices(tcon);
	//show/hide options for rental
	//$('.tr_'+id).toggle();
}

function useAddress(){
	$("[name='street']").val($("[name='eventstreet']").val());
	$("[name='city']").val($("[name='eventcity']").val());
	$("[name='state']").val($("[name='eventstate']").val());
	$('select[name=state] option[value='+$("[name='state']").val()+']').attr('selected', '');
	$('select[name=state] option[value='+$("[name='eventstate']").val()+']').attr('selected', 'selected');
	
	$("[name='zip']").val($("[name='eventzip']").val());
	return true;
}
function useAddress2(){
	$("[name='eventstreet']").val($("[name='street']").val());
	$("[name='eventcity']").val($("[name='city']").val());
	$("[name='eventstate']").val($("[name='state']").val());
	$('select[name=eventstate] option[value='+$("[name='eventstate']").val()+']').attr('selected', '');
	$('select[name=eventstate] option[value='+$("[name='state']").val()+']').attr('selected', 'selected');
	$("[name='eventzip']").val($("[name='zip']").val());
	return true;
}

function exportLeads(){
	var vpreset = encodeURIComponent($("#preset").val());
	var vorganization = encodeURIComponent($("#organization").val());
	var vstatus = ''; 
	$("input[name='status[]']").each(function(){ 
		if(this.checked){ 
			vstatus += "&status[]=" + encodeURIComponent(this.value); 
		} 
	});
	//var vname = encodeURIComponent($("a#name").text());
	var vdate = encodeURIComponent($("input#date").val());
	var vkeyword = encodeURIComponent($("input#keyword").val());
	//var vquantity = encodeURIComponent($("select#quantity").val());
	//var vrecstart = encodeURIComponent($("input#recstart").val());
	var vrowsort = encodeURIComponent($("input#rowsort").val());
	var vrowdir = encodeURIComponent($("input#rowdir").val());
	var exurl = "./exportleads.php?preset="+vpreset+"&organization="+vorganization+vstatus+"&date="+vdate+"&keyword="+vkeyword+"&rowsort="+vrowsort+"&rowdir="+vrowdir;  
	//alert(exurl);
	window.open(exurl,"ExportLeads");
	return true;
}

function viewReport(){
	var vpreset = encodeURIComponent($("#preset").val());
	var vorganization = encodeURIComponent($("#organization").val());
	var vstatus = ''; 
	$("input[name='status[]']").each(function(){ 
		if(this.checked){ 
			vstatus += "&status[]=" + encodeURIComponent(this.value); 
		} 
	});
	//var vname = encodeURIComponent($("a#name").text());
	var vdate = encodeURIComponent($("input#date").val());
	var vkeyword = encodeURIComponent($("input#keyword").val());
	//var vquantity = encodeURIComponent($("select#quantity").val());
	//var vrecstart = encodeURIComponent($("input#recstart").val());
	var selected_rentals = encodeURIComponent($("input[name=selected_rentals]").val());
	var selected_locations = encodeURIComponent($("input[name=selected_locations]").val());
	var selected_salesrep = encodeURIComponent($("input[name=selected_salesrep]").val());
	var vrowsort = encodeURIComponent($("input#rowsort").val());
	var vrowdir = encodeURIComponent($("input#rowdir").val());
	var vreport = encodeURIComponent($("select[name=report]").val());
	var exurl = "./viewreport.php?preset="+vpreset+"&organization="+vorganization+vstatus+"&date="+vdate+"&keyword="+vkeyword+"&rowsort="+vrowsort+"&rowdir="+vrowdir+"&report="+vreport+"&selected_rentals="+selected_rentals+"&selected_locations="+selected_locations+"&selected_salesrep="+selected_salesrep;  
	//alert(exurl);
	window.open(exurl,"Report");
	return true;
}

function changeContract(){
	var leadid = $("input#leadid").val();
	var contract = $("select[name='contract']").val();
  $('#tx_qpagetext').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/updatecontract.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&contract='+contract,
	    dataType: 'xml',
	    //timeout: 3000,
	    error: function(){
				$('#tx_qpagetext').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
	  		if($("result",xml).text()!='<p>Error exists!</p>'){
	  			//not showing contract anymore, but code still exists to, only changing select box options
  				//$("#tx_qpagetext").html($("contractdisp",xml).text());
  				$("select[name=viewselect_0]").replaceWith($("selectbox",xml).text());
  				$("input[name=emailsubject]").val($("subject",xml).text());
  				$("textarea[name=emailmessage]").val($("body",xml).text()); //this changes the content if xinha hasn't loaded yet
  				xinha_editors.emailmessage.setHTML($("body",xml).text());
  			}else{
  				$("#output1").html($("errorhtml",xml).text());
	  		}
				$('#tx_qpagetext').unblock();
  		}
	});
}

function addContract(){
	var leadid = $("input#leadid").val();
	var totalrows = $('#contract_table .settingsRow01').size();
  //$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
  $('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/addcontracts.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&totalrows='+totalrows,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
  			$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(txt){
	    	if(txt!='Error: Code exists!'){
    			$("#nocontracts").hide();
    			$("#addcontracts").before(txt);
    			if($('div#contract .settingsRow01').size()==1){
    				$("input[name='ctractive']").attr("checked",true);
    			}
   			}
  			//$.unblockUI();
  			$('#pagecontent').unblock();
  		}
	});
}

function delContract(rownum){
	//alert($("tr#row_"+rownum+" input[name='contractid[]']").val());
	if($("input[name='contractstodel']").val()){
		$("input[name='contractstodel']").val($("input[name='contractstodel']").val()+','+$("tr#row_"+rownum+" input[name='contractid[]']").val());
	}else{
		$("input[name='contractstodel']").val($("tr#row_"+rownum+" input[name='contractid[]']").val());
	}
	//alert($("input[name='contractstodel']").val());
	$('tr#row_'+rownum).remove();
}

function addPayment(){
	var leadid = $("input#leadid").val();
	var totalrows = $('#payment_table .settingsRow01').size();
  //$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
  $('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/addpayments.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&totalrows='+totalrows,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
  			$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(txt){
	    	if(txt!='Error: Code exists!'){
    			$("#nopayments").hide();
    			$("#addpayments").before(txt);
   			}
				if($('.dpbutton')){
					$('.dpbutton').datepicker({dateFormat: 'm/d/yy', speed: 'fast', 
			  		showOn: 'both', buttonImage: '../images/calendar.gif', buttonImageOnly: true,	buttonText: 'Calendar'});
			  }
  			//$.unblockUI();
  			$('#pagecontent').unblock();
  		}
	});
}

function delPayment(rownum){
	if($("input[name='paymentstodel']").val()){
		$("input[name='paymentstodel']").val($("input[name='paymentstodel']").val()+','+$("tr#prow_"+rownum+" input[name='paymentid[]']").val());
	}else{
		$("input[name='paymentstodel']").val($("tr#prow_"+rownum+" input[name='paymentid[]']").val());
	}
	$('tr#prow_'+rownum).remove();
}

function viewContract(id){
	var leadid=$('input#leadid').val();
	var contactid=$('input#contactid').val();
	var ctemail=$('#ctemail').text();
	var ctrstatus=$('select[name=viewselect_'+id+']').val();
	var page = '../quotes/contract.php?leadid='+leadid+'&contactid='+contactid+'&custcontractid='+id+'&ctrstatus='+ctrstatus;
	var winprefs = 'menubar=1,toolbar=1,scrollbars=1,width=875';
	if(id!=0){
		window.open(page,'win1',winprefs);
	}else{
		page = '../quotes/contract.php?leadid='+leadid+'&contactid='+contactid+'&custcontractid='+$('select[name=contract]').val()+'&ctrstatus='+ctrstatus;
		window.open(page,'',winprefs);
	}
}

function sendContract(){
	var leadid=$('input#leadid').val();
	var contactid=$('input#contactid').val();
	var contractid=$('select[name=contract]').val();
	var emailfrom = $("input[name=emailfrom]").val();
	var emailto = $("input[name=emailto]").val();
	var emailcc = $("input[name=emailcc]").val();
	var emailbcc = $("input[name=emailbcc]").val();
	var emailsubject = $("input[name=emailsubject]").val();
	var emailmessage = escape(xinha_editors.emailmessage.getHTML());
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Sending Email...</h1>'});
  //$('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/sendcontract.php',
	    type: 'POST',
	    data: 'contractid='+contractid+'&contactid='+contactid+'&leadid='+leadid+'&emailfrom='+emailfrom+'&emailto='+emailto+'&emailcc='+emailcc+'&emailbcc='+emailbcc+'&emailsubject='+emailsubject+'&emailmessage='+emailmessage,
	    dataType: 'xml',
	    //timeout: 3000,
	    error: function(){
  			$.unblockUI();
  			//$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
	    	if($("result",xml).text()=='not sent'){
   				alert('Error sending email! Please try again.');
   			}else if($("result",xml).text()=='updated'){
   				$("#statusrow").html($("statusrow",xml).text());
   				$('#contractsent').replaceWith($("contractsent",xml).text());
					$('#row_'+leadid).replaceWith($("tablerow",xml).text());
					$("tr#row_"+leadid).addClass("rowSelected");
					$('#ctrsend').hide();
   			}else if($("result",xml).text()=='sent'){
					$('#ctrsend').hide();
   			}
  			$.unblockUI();
  			//$('#pagecontent').unblock();
  		}
	});
}

function sendQuote(){
	var leadid = $("input#leadid").val();
	var emailfrom = $("input[name=q_emailfrom]").val();
	var emailto = $("input[name=q_emailto]").val();
	var emailcc = $("input[name=q_emailcc]").val();
	var emailbcc = $("input[name=q_emailbcc]").val();
	var emailsubject = $("input[name=q_emailsubject]").val();
	var emailmessage = escape(xinha_editors.quoteemail.getHTML());
  $.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Sending Email...</h1>'});
  //$('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/sendquote.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&emailfrom='+emailfrom+'&emailto='+emailto+'&emailcc='+emailcc+'&emailbcc='+emailbcc+'&emailsubject='+emailsubject+'&emailmessage='+emailmessage,
	    dataType: 'xml',
	    //timeout: 3000,
	    error: function(){
  			$.unblockUI();
  			//$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
	    	if($("result",xml).text()=='not sent'){
   				alert('Error sending email! Please try again.');
   			}else if($("result",xml).text()=='sent'){
   				tb_remove();
					$('#ctrsend').hide();
   			}
  			$.unblockUI();
  			//$('#pagecontent').unblock();
  		}
	});
}

function saveTemplate(){
	var leadid = $("input#leadid").val();
	var contracttemp = $('select[name=contracttemp]').val();
	var contracttext = escape(xinha_editors.text.getHTML());
  //$.blockUI({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
  $('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/savecusttemp.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&contracttemp='+contracttemp+'&contracttext='+contracttext,
	    dataType: 'xml',
	    //timeout: 3000,
	    error: function(){
  			$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
	    	if($("errorhtml",xml).text()!='Error Exists!'){
	    		$('select[name=contracttemp]').replaceWith($("contracttemp",xml).text());
	    		//$('select.ctrtemp').replaceWith($("ctrtemp",xml).text());
   			}
  			//$.unblockUI();
  			$('#pagecontent').unblock();
  		}
	});
}

function recalc_disable(tcon){
	if($('input[name=recalculate]:checked').length){
		$('.recalc_disable').attr('disabled','disabled');
	}else{
		$('.recalc_disable.ridequotes').each(function(){
			var ridequotes_id=$(this).attr('id');
			var rental_id=ridequotes_id.replace('ridequotes','rental');
			if($('#'+rental_id).attr("checked")===true){
				$(this).removeAttr('disabled');
			}
		});
		$('.recalc_disable').not('.ridequotes').removeAttr('disabled');
		changePrices(tcon);
	}
}
function more_qty_leads(qty_id){
	var max_qty_id=qty_id.replace('qty','max_qty');
	var more_text=$('#'+qty_id).val();
	if(more_text.search('\\+')!=-1){
		$('#'+qty_id).removeOption(/\+/);
		var increment=$('#'+qty_id+' > option').val();
		var more=parseInt(more_text.replace('+','')/increment);
		var first_plus='+'+String(10*increment);
		var second_plus='+'+String(100*increment);
		var last_value=$('#'+qty_id+' > option').filter(":last").val();
		var page_max_qty=($('#'+max_qty_id).length==0) ? 0 : $('#'+max_qty_id).val();
		var max_qty=Math.max(page_max_qty,10000);
		for(i=1; i<=more; i++){
			var new_value=parseInt(last_value)+increment*i;
			if(new_value > max_qty){ break; }
			$('#'+qty_id).addOption(new_value,new_value,false);
		}
		if(new_value >= max_qty){
			new_value=max_qty;
		}else{
	    $('#'+qty_id).append($('<option></option>').val(first_plus).html(first_plus));
	    $('#'+qty_id).append($('<option></option>').val(second_plus).html(second_plus));
		}
		$('#'+qty_id).selectOptions(String(new_value),true);
	}
}
function get_rental_times(){
	var rental_id=$("select[name=tm_rental]").val();
	if(rental_id!="select"){
		if($("#rentalstarttime_"+rental_id).val().length>0){
			var starttime_arr = $("#rentalstarttime_"+rental_id).val().split(" ");
			var startdate = starttime_arr[0];
			var starttime = starttime_arr[1];
		}else{
			var startdate = $("input[name=startdate]").val();
			var starttime = $("input[name=starttime]").val();
		}
		$("input[name=tm_rentalstartdate]").val(startdate);
		$("input[name=tm_rentalstarttime]").val(starttime);
		if($("#rentalendtime_"+rental_id).val().length>0){
			var endtime_arr = $("#rentalendtime_"+rental_id).val().split(" ");
			var enddate = endtime_arr[0];
			var endtime = endtime_arr[1];
		}else{
			var enddate = $("input[name=enddate]").val();
			var endtime = $("input[name=endtime]").val();
		}
		$("input[name=tm_rentalenddate]").val(enddate);
		$("input[name=tm_rentalendtime]").val(endtime);
	}else{
		$("input[name=tm_rentalstartdate]").val("");
		$("input[name=tm_rentalstarttime]").val("");
		$("input[name=tm_rentalenddate]").val("");
		$("input[name=tm_rentalendtime]").val("");
	}
	return true;
}
function saveTimes(){
	var rental_id=$("select[name=tm_rental]").val();
	if(rental_id!="select"){
		var startdate = $("input[name=tm_rentalstartdate]").val();
		var starttime = $("input[name=tm_rentalstarttime]").val().replace(" ","");
		var enddate = $("input[name=tm_rentalenddate]").val();
		var endtime = $("input[name=tm_rentalendtime]").val().replace(" ","");
		$("#rentalstarttime_"+rental_id).val(startdate+" "+starttime);
		$("#rentalendtime_"+rental_id).val(enddate+" "+endtime);
		//show/hide clock icon next to rental_id
		//alert(starttime+' '+$("input[name=starttime]").val().replace(" ","")+' '+endtime+' '+$("input[name=endtime]").val().replace(" ",""));
		if(startdate==$("input[name=startdate]").val() && (starttime==$("input[name=starttime]").val() | starttime==$("input[name=starttime]").val().replace(" ","")) && enddate==$("input[name=enddate]").val() && (endtime==$("input[name=endtime]").val() | endtime==$("input[name=endtime]").val().replace(" ",""))){
			$('#times_'+rental_id).hide();
		}else{
			$('#times_'+rental_id).show();
		}
		$("#tm_buttons").html("<div id=\'tm_message\' style=\'color:green;font-weight:bold;\'>Successful Change!</div>");
		setTimeout(function(){$("#tm_message").remove();},3000);
	}
	return true;
}
function updateTimes(){
	$("input[name='rentals[]']").each(function(){
		var rental_id=$(this).attr('id');
		var rentalstarttime_id=rental_id.replace('rental','rentalstarttime');
		var rentalendtime_id=rental_id.replace('rental','rentalendtime');
		var startdate = $("input[name=startdate]").val();
		var starttime = $("input[name=starttime]").val().replace(" ","");
		var enddate = $("input[name=enddate]").val();
		var endtime = $("input[name=endtime]").val().replace(" ","");
		$("#"+rentalstarttime_id).val(startdate+" "+starttime);
		$("#"+rentalendtime_id).val(enddate+" "+endtime);
  });
}

function changeContractname(select_id){
	var ctr_id=select_id.replace('ctrtemp','ctrname');
	$("#"+ctr_id).val($("#"+select_id).val());
}

function resendEmail(spooler_id){
	var leadid = $("input#leadid").val();
  $('#pagecontent').block({overlayCSS: { backgroundColor: '#fff', opacity: '0.1' }, pageMessage: '<h1>Processing...</h1>'});
	$.ajax({
	    url: '../include/resend_email.php',
	    type: 'POST',
	    data: 'leadid='+leadid+'&spooler_id='+spooler_id,
	    dataType: 'html',
	    //timeout: 3000,
	    error: function(){
  			$('#pagecontent').unblock();
	      //alert('Please try again or refresh the page to see if you are still logged in.');
	    },
	    success: function(xml){
	    	if($("errorhtml",xml).text()!='Error Exists!'){
	    		//$('select[name=contracttemp]').replaceWith($("contracttemp",xml).text());
   			}
  			//$.unblockUI();
  			$('#pagecontent').unblock();
  		}
	});
}

function ctrSend(){
	$('#ctrsend').toggle();
	if($('.htmlarea').length==0){
		//initialize xinha editor
		$.getScript("../xinha/xinha_custom.js", function(){
		   // here you can use anything you defined in the loaded script
		   xinha_init();
		});
	}
	changeContract();
	window.location.href = "#ctremail";
}

function customertypeChange(){
	var resident_array = new Array('Residential');
	if(jQuery.inArray($('select[name=customertype]').val(),resident_array)!=-1){
		$('#notapplicable').attr('checked','checked');
	}else{
		$('#notapplicable').removeAttr('checked');
	}
	disable_inputbox($('#notapplicable')[0],$('#eventorganization')[0]);
}
