

var userId = "";
var userNickname = ""; 
var userEmail = "";
var enterNewTitle = "Enter title";
var deleteImg = "<img class='imgDelete' src='images/delete3.png' width='12' height='12' border='0'/>";
var TR_TYPE_PARAGRAPH = 1;
var TR_TYPE_LINE = 2;
var BGCOLOR_INPUT_CHANGED = "#707070";
var BGCOLOR_INPUT_CHANGING = "#3F30C9";
var imgMoveSrc = "images/moveLine.png";
var imgMoveHereSrc = "images/moveHere.png";
var imgMoveMeSrc = "images/moveLine.png";
var moveIsOnn = false;
  
var BUDGET_FORMAT_ITEM = "1";
var BUDGET_FORMAT_MONTHLY = "2";
var KEYCODE_ESC = 27; 

var saveAllP = "";
var saveAllLines = "";
var globalValue = false;
var globalShowDashbord = false;
var globalIsNewBudget = false;
var globalHtml = "";

var newLinePrefix = "NewLine";
var lastRowId = 0;

var rowCounter = 0;
var budgetUserId = -1;
var MIN_NICKNAME = 5;
var isEmbed = false;
var isSavingNewBudget = false;
var isCreatingFromDb = false;
var ITEM_SEPERATE_1 = "#^^#";
var ITEM_SEPERATE_2 = "#@@#";

var FTYPE_TEXT = "0";
var FTYPE_NUMBER = "1";
var FTYPE_CURRENCY = "2";
var FTYPE_DATE = "3";
var FTYPE_LONG_TEXT = "4";
var FTYPE_LIST = "5";
var FTYPE_LINK = "6";
var arrTrackerDates = [];

/*
$(window).resize(function() {
  showAdLeft();
});

function showAdLeft(){
	if ($(window).width() > 1219){ 
		$("#divAdLeft").show();
	}
	else{ 
		$("#divAdLeft").hide();	
	}
}
*/

$(document).ready(function(){

	if (isEmbed){
		//$("body1").css("background-image","url('images/pattern.png'");
		//$("body1").css("background-repeat","repeat");	
		$('#body1').css("background","transparent");
	}
	
	//showAdLeft();
	
	$("#aSignUp").click(function(event){
		var saveBudget = false;
		signUp(saveBudget);
		event.preventDefault();
    });

	$("#aLogin").click(function(event){
		showLogin(false, true);
		event.preventDefault();
    });
	
	$("#spanDashboard").hide(); 
	
	$('#registerWindow').animate({
		opacity: .8,
		height: '99%',
		width:  '99%'
	});
	
	$('.imgSpreadsheet').animate({
		opacity: .4
	});
	
	$('.imgSpreadsheetIcon').animate({
		opacity: .7
	});
	
	doLogin("","", false, false);
	$("#spanHdrIcons").show(); 
	
	


	//set up budget default values
	
	
	if (document.getElementById('budgetId')!=null){

		// create the lines 
		
		var trTitle = "";
		var trType = 0;
		var parentRowId = -1;

		isCreatingFromDb = true;
		for (var rowId=0; rowId < rowCounter; rowId++) {		
				
			if (document.getElementById('spnTrTitle_' + rowId)!=null){
				trType = $("#spnTrType_" + rowId).html();		
				
				if (trType==TR_TYPE_PARAGRAPH){
					parentRowId = rowId;
					createNewParagraph("Last", 1, true, rowId);
				}
				else if (trType==TR_TYPE_LINE){
					createNewLine(parentRowId, newLinePrefix + parentRowId, 1, true, false, rowId);
				}				
			}
		}
		
		isCreatingFromDb = false;		
		calcTotal(false);
		//implementDate('inpDatePicker'); 
		//$(".inpDatePicker").css("width","100px");
		
		
		setColorSchemeValues();
		$(".budgetIsLoading").hide(10);
		
		if (isEmbed){
			$(".budgetContainer").fadeIn(250);
			saveValuesEmbed();
			//$("body").css("background", "white");
			//$('.body1').css('backgroundImage' , "");
			//$('.body1').css('background-image' , "url('')");
			 
			// $("body").removeClass('body1').addClass("body2");
			
				
			$(".aSaveEmbed").click(function(event){
				var saveBudget = false;
				
				saveValuesEmbed();
				
				
				
			});
 
		}
		else {
			if (!isTracker()){ 
				$(".budgetContainer").fadeIn(1500);
				
				var embedUrl = "?page=embed&sheetId=" + $("#sheetTempId").val() + "&width=" + (getSheetWidth() + 10);
				$("#aEmbed").attr("href",embedUrl);
			}
			
			
		}
			
		if (isEmbed){
			setSheetWidth();
		}

		if (isTracker()){
			$('#trackerDate').val(getCurrentDate() );
			implementDate('trackerDate');
			setTrackerDates($('#trackerDate').val() );
			$(".trackerContainer").fadeIn(1000);
			$("#aSaveBudget").hide();		

			showFullscreen();
			
			var rowKey;
			var rowTitle;
			var parentRowKey;
			for (var rowId=0; rowId < rowCounter; rowId++) {		
					
				if (document.getElementById('spnTrKey_' + rowId)!=null){
					if (trType==TR_TYPE_PARAGRAPH){
						parentRowKey = rowKey;
					}
					
					trType = $("#spnTrType_" + rowId).html();		
					rowTitle = $("#spnTrTitle_" + rowId).html();		
					rowKey = $("#spnTrKey_" + rowId).val();
					
					createTrackerComboArr(parentRowKey, rowKey, trType, rowTitle);
				}  
			}
			createTrackerQuickAdd();
			//alert(arrTrackerComboParent);
			//alert(arrTrackerCombo);
		}
		
	}
	
	setDesignValues();	
	
});

function implementDate(dateName){
	
	$('#' + dateName).DatePicker({
		format:'m/d/Y',
		date: $('#' + dateName).val(),
		current: getTrackerDate($('#' + dateName).val() ),
		starts: 1,
		position: 'r',
		showWeek: false,
		weekHeader: '',
		onBeforeShow: function(){
			$('#' + dateName).DatePickerSetDate($('#' + dateName).val(), true);
		},
		onChange: function(formated, dates){
				$('#' + dateName).DatePickerHide();
				
				if (formated.toString() != $('#' + dateName).val() ){
					$('#' + dateName).val(formated);
					if (isTracker()){
						setTrackerDates( $('#' + dateName).val() );
					}
				}
		}
	});
}

function setNewPTitle(){
	$(".inpLineTitle").focus(function() {
		if ($(this).val()==enterNewTitle){
			$(this).val("");
			$(this).css("color", "black");
		}
	});

	$(".inpLineTitle").focusout(function() {
		var str = jQuery.trim($(this).val());
		if (str == ""){
			$(this).val(enterNewTitle);
			$(this).css("color", "blue");
		}
	});
	
	$(".inpValue").focus(function(){     
		this.select(); 
	});
	


}

function handleItemPrice(){
	$(".inpLineTitle").focus(function() {
		if ($(this).val()==enterNewTitle){
			$(this).val("");
			$(this).css("color", "black");
		}
	});

	$(".inpLineTitle").focusout(function() {
		var str = jQuery.trim($(this).val());
		if (str == ""){
			$(this).val(enterNewTitle);
			$(this).css("color", "gainsboro");
		}
	});

}



jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
		

function signUp(saveCurrentBudget){
	var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;
	
	html += "<div style='text-align: center;'>";
	html += "<span class='smallWindowTitle'>Free account - Sign up to Calculito</span><br>";
	html += "</div><br>";

	html += "<table id='tblSignUp' bgcolor='gainsboro' width='100%' style='padding:5px; font-size:13px; line-height: 24px; border: 1px solid #708090;' >";

	html += "<tr valign='top'><td colspan='4'><b><span id='emailMsg' style='color:green;'></span></b></td></tr>";
	html += "<tr><td><b>Email </b></td>";	
	html += "<td nowrap><input type='text' id='newEmail' class='inputSingUp' > </td><td><img id='emailAp' src='images/approve.gif' /> </td>";	
	html += "<td style='color: #808080;'>Other users can't see your email</td></tr>";	

	html += "<tr><td colspan='4'><b><span id='nicknameMsg' style='color:green;'></span></b></td></tr>";
	html += "<tr><td><b>Nickname </b></td>";	
	html += "<td nowrap><input type='text' id='newNickname' class='inputSingUp' > </td><td><img id='nicknameAp' src='images/approve.gif' /> </td></tr>";	

	html += "<tr><td colspan='4'><b><span id='passMsg' style='color:green;'></span></b></td></tr>";
	html += "<tr><td><b>Password </b></td>";	
	html += "<td nowrap><input type='password' id='newPass' class='inputSingUp' > </td><td><img id='passAp' src='images/approve.gif' /> </td>";	
	html += "<td style='color: #808080;'> 6 characters or more</td></tr>";	

	html += "<tr><td colspan='4'><b><span id='repassMsg' style='color:green;'></span></b></td></tr>";
	html += "<tr><td><b>Re-Password </b></td>";	
	html += "<td nowrap><input type='password' id='rePass' class='inputSingUp' > </td><td><img id='repassAp' src='images/approve.gif' /> </td></tr>";	
	html += "</table><br><br>";	
	html += "<div style='text-align: center;'>";
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitSignUpForm' />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideSignUp' />";	
	html += "</div>";
	html += "<div style='padding-top: 40px; font-size: 12px; font-weight: bold;'>";
	html += "Already a user? &nbsp;&nbsp;";	
	html += "<a href='javascript:showLogin(" + saveCurrentBudget + ", true);' class='aNotAUser' >Sign In</a>";	
	html += "</b><br></div>";	

	
	$("#registerInner").html(html);
	
	$('#submitSignUp').css('color', 'green');
	$('#submitSignUp').css('font-weight', 'bold');
	
	if (saveCurrentBudget){
		$("#submitSignUpForm").click(function(event) {   
			
			doSignUp(true); 
			event.preventDefault();
		});   
	}
	else {
		$("#submitSignUpForm").click(function(event) {   
			doSignUp(false); 
			event.preventDefault();
		});   
	}
	
	$("#hideSignUp").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$("#newEmail").change(function() {   
		validateEmail();
	});   

	$("#newNickname").change(function() {   
		validateNickname(); 
	});   
   
	$("#newPass").change(function() {   
		validatePass();
	});   

	$("#rePass").change(function() {   
		validateRepass();
	});   
	
	$("#emailAp").hide();
	$("#nicknameAp").hide();
	$("#passAp").hide();
	$("#repassAp").hide();
	
	$('#registerContent').animate({		
		width:  '490px'
	});
	
	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast");
	
	$('html, body').animate({scrollTop:0}, 'fast'); 
}

var validEmail = 0;
function validateEmail(){
	var newEmail = $("input#newEmail").val();
	validEmail = 0;
	document.getElementById("emailMsg").innerHTML = "";	
	$("#emailAp").hide();
	
	if (isValidEmail(newEmail)){
		var time1 = get_time();	
		$.get("checkEmail.php?emailAddress=" + newEmail + "&t=" + time1, function(data) {
		
			validEmail=data;
			if (validEmail=="3"){
				document.getElementById("emailMsg").innerHTML = "The email address is already registered to calculito";
			}
			else if (validEmail=="0"){
				document.getElementById("emailMsg").innerHTML = "Not a valid email address";
			}
			else if (validEmail=="1"){
				$("#emailAp").show();;
			}
		});
	}
	else {
		document.getElementById("emailMsg").innerHTML = "Not a valid email address";	
	}
	
	return validEmail;
}

var validNickname = false;
function validateNickname(){
		$("#nicknameAp").hide();
        validNickname = false;
		document.getElementById("nicknameMsg").innerHTML = "";
		var newNickname = document.getElementById("newNickname").value;
		if (newNickname.length < MIN_NICKNAME){
			document.getElementById("nicknameMsg").innerHTML = "Please enter your nickname - " + MIN_NICKNAME + " characters or more";
		}
		else {
			validNickname = true;
			$("#nicknameAp").show();
		}
}

var validPass = false;
function validatePass(){
		$("#passAp").hide();
		validPass = false;
		document.getElementById("passMsg").innerHTML = "";
		var newPass = $.trim( document.getElementById("newPass").value );
		if ((newPass.length < 6)){
			document.getElementById("passMsg").innerHTML = "Password must be 6 characters or more";
		} else {
			validPass = true;
			$("#passAp").show();
			//validateRepass();
		}
}

var validRepass = false;
function validateRepass(){
		$("#repassAp").hide();
		validRepass = false;
		document.getElementById("repassMsg").innerHTML = "";
		var rePass = document.getElementById("rePass").value;
		var newPass = document.getElementById("newPass").value;
		if ((newPass != rePass)){
			document.getElementById("repassMsg").innerHTML = "Re-Password don't match";
		} else if (validPass) {
			validRepass = true;
			$("#repassAp").show();
		}
}

//var tempUserEmail, tempUserPass;
function doSignUp(saveBudget){
	
	if  (validEmail!="1"){  validateEmail(); }
	if (!validNickname){ validateNickname(); }
	if (!validPass){ validatePass(); }
	if (!validRepass){ validateRepass(); }

	if ( $("#repassAp").val() != $("#newPass").val() ) {
		validateRepass();
	}
	
	
	if (validNickname && validPass && validRepass && (validEmail=="1")){
		
		var time1 = get_time();		
		var dataString = "";
		dataString += "newEmail=" + $("#newEmail").val();
		dataString += "&newPass=" + $("#newPass").val();
		dataString += "&newNickname=" + $("#newNickname").val();			
		dataString += "&userT=" + time1;					
		
		globalValue = saveBudget;
		
		$.ajax({   
			type: "POST",   
			url: "newUser.php",   
			context: document.body,
			data: dataString,   
			success: function(){  						
				doLogin($("#newEmail").val(), $("#newPass").val() , globalValue, false );
				hidwWindow(200);							
			}
		});

		validEmail = 0;
		validNickname = false;
		validPass = false;
		validRepass = false;
	
	}
}


function showLogin(saveBudget, showDash){
	var html = "";
	isSavingNewBudget = saveBudget;

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Login to Calculito</span><br><br>";
	html += "<table id='tblSignUp' bgcolor='gainsboro' style='padding:5px; font-size:13px; line-height: 24px; border: 1px solid #708090;' >";

	html += "<tr><td><b>Email </b></td>";	
	html += "<td nowrap><input type='text' id='newEmail' class='inputSingUp' ></td>";	
	html += "</tr>";	

	html += "<tr><td><b>Password </b></td>";	
	html += "<td nowrap><input type='password' id='newPass' class='inputSingUp' ></td>";	
	html += "</tr>";	
	
	html += "<tr><td colspan='4' align='center' ><b><span id='passMsg' style='color:red; padding: 3px;'></span></b></td></tr>";

	html += "</table><br>";	
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitLoginWindow' />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideLogin' />";	
	html += "<div style='padding-top: 42px; font-size: 12px; font-weight: bold;'>";
	html += "Not a user? &nbsp;&nbsp;";	
	html += "<a href='javascript:signUp(" + saveBudget + ");' class='aNotAUser' >Sign Up Now</a>";	
	html += "<br><br>";	
	html += "Forgot your password? &nbsp;&nbsp;";	
	html += "<a href='javascript:forgetPass();' class='aNotAUser' >Click here</a>";	
	html += "<br></div>";	
	

	

	document.getElementById("registerInner").innerHTML = html;
	
	$('#submitLoginWindow').css('color', 'green');
	$('#submitLoginWindow').css('font-weight', 'bold');

	$("#submitLoginWindow").click(function(event) {   
		doLogin($('#newEmail').val() , $('#newPass').val() , isSavingNewBudget, showDash); 
		event.preventDefault();
	});   

	$('#newPass').keypress(function(e) {   
		if (e.keyCode == '13') {     
			doLogin($('#newEmail').val() , $('#newPass').val() , isSavingNewBudget, showDash); 			
			
			e.preventDefault();      
		} 
	}); 
	
	$('#newEmail').keypress(function(e) {   
		if (e.keyCode == '13') {     
			doLogin($('#newEmail').val() , $('#newPass').val() , isSavingNewBudget, showDash); 			
			e.preventDefault();      
		} 
	}); 	
	
	$("#hideLogin").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$('#registerContent').animate({		
		width:  '340px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast");
	$("#passMsg").hide();
	$('html, body').animate({scrollTop:0}, 'fast'); 
	
}

function doLogin(userEmailAddress,userPass, saveBudget, showDashboard){
	$("#passMsg").hide();
	
	var time1 = get_time();		
	$("#submitLoginWindow").attr('disabled', 'disabled'); 	
	
	globalValue = saveBudget;
	globalShowDashborad = showDashboard;
	$.get("login.php?user_email=" + userEmailAddress + "&user_password=" + userPass + "&t=" + time1, function(data) {
		
		if (isLoginLegal(data)){
			("#submitLoginWindow")
			setLoginHdr(true);
			//alert( $("#submitLoginWindow") );
			
			if (globalValue==true){ 
				saveCurrentBudget() ;
			}
			else {
				if (globalShowDashborad){
					document.location.href = "?userId=" + userId;			
				}
			}
			globalShowDashborad = false;
			
		}
		else {
		
			$("#submitLoginWindow").removeAttr('disabled');

			$("#passMsg").html("Invalid ID or password");
			$("#passMsg").show();
		}
		
	});
}


function setLoginHdr(isLogin){
		
	hidwWindow();
	
	$("#spanSignUp").hide(50);
	$("#spanDashboard").show(50);
	$("#aLogin").html("LOGOUT"); 
	
	$('#aLogin').unbind('click');
	$("#aLogin").click(function(event){
		doLogout();
		event.preventDefault();
	});	
		
	$('#aDashboard').attr("href","?userId=" + userId);	
	$('#aDashboard').css("color","green");	
	$("#spanUserEmail").html(" &nbsp;&nbsp; " + userEmail + " &nbsp;"); 
	
	if (document.getElementById('budgetId')!=null){
		$("#divBudgetTitle").click(function(event){
			
			if (isMyBudget()) {
				$(this).hide(20);
				
				$("#divBudgetTitleEdit").show();
				$("#inpEditTitle").val($(this).html());
				$("#inpEditTitle").css("width", "200px");
				$("#inpEditTitle").css("height", "18px");
				$("#inpEditTitle").focus();
			}
		});
		
		$("#inpEditTitle").focusout(function() {
			var str = $(this).val();
			if (str.length < 2){
				$(this).val("no title");
			}
			$("#divBudgetTitleEdit").hide();
			$("#divBudgetTitle").show();
			$("#divBudgetTitle").html( $(this).val() );
		
		});
		
		
		$("#inpEditTitle").change(function() {
			budgetIsChanged();
		});
		

		$("#divBudgetDesc").click(function(event){
			
			if (isMyBudget()) {
				$(this).hide(20);
				
				$("#txtBudgetDesc").show();

				//return parseFloat(  newValue.replace(/,/g,"") ); 
				var newValue = br2nl( $(this).html());
				//var txtWithLineBreak =  newValue.replace(/chr(13)/g,"\n")
				
				$("#txtBudgetDesc").val( newValue);
				$("#txtBudgetDesc").focus();
			}
		});
		
		$("#txtBudgetDesc").focusout(function() {
			var str = $(this).val();
			if (str.length < 2){
				$(this).val("no title");
			}
			
			var newValue = nl2br( $(this).val() );
			

			$("#txtBudgetDesc").hide();
			$("#divBudgetDesc").show();
			$("#divBudgetDesc").html( newValue );
		
		});
		
		$("#txtBudgetDesc").change(function() {
			budgetIsChanged();
		});
		
		$("#selectedPrivacyId").change(function() {
			budgetIsChanged();
		});
		
		$("#selectedCategoryId").change(function() {
			budgetIsChanged();
		});
		
		if (isMyBudget()) {
			$('#divBudgetTitle').css( 'cursor', 'pointer' );
			$('#divBudgetDesc').css( 'cursor', 'pointer' );		
			
		}	
	}		
}

function doLogout(){
	
	var time1 = get_time();		
	$.get("logout.php?t1=" + time1, function(data) {
		location.reload();
	});
}

function isLoginLegal(loginData){
	
	var loginResult = false;
	var pos1 = loginData.indexOf("#");
	
	if (pos1 > 0){
		userId = loginData.substr(0, pos1);
	
		if (IsNumeric(userId)){
			loginResult = true;
 			
			//var str = loginData.substr(pos1 + 1);
			var pos2 = loginData.indexOf("&&");
			userNickname = loginData.substr(pos1 + 1, pos2 - 3);
			userEmail = loginData.substr(pos2 + 2);
	
		}	
	}
	return loginResult;
}

function hidwWindow(){

	$("#registerWindow").hide();
	$("#registerContent").fadeOut(250);
	$("#registerInner").html("") ;

}

function hidwWindowFast(){

	$("#registerWindow").hide();
	$("#registerContent").hide();
	$("#registerInner").html("") ;

}


function isValidEmail(str) {
		return (str.indexOf(".") > 1) && (str.indexOf("@") > 0);
}

function IsNumeric(sText){

	   var ValidChars = "0123456789.";
	   var IsNumber=true;
	   var Char;
	   
	   var myNumber = sText;
	   if (myNumber.toString().indexOf("-") == 0){
			myNumber = myNumber.substr(1, (myNumber.length - 1));
	   
	   }
	   
	   if (myNumber.length==0){
		IsNumber = false;
	   }

	 
	   for (i = 0; i < myNumber.length && IsNumber == true; i++) 
		  { 
		  Char = myNumber.charAt(i); 
		  if (ValidChars.indexOf(Char) == -1) 
			 {
			 IsNumber = false;
			 }
		  }
		  return IsNumber;	   
	}




function get_time()
 { 
    Stamp = new Date(); 
    var hours;   var mins;   var secs;  var time1; var milsec;
    hours = Stamp.getHours(); 
    mins = Stamp.getMinutes(); 
    secs = Stamp.getSeconds(); 
    milsec = Stamp.getMilliseconds(); 
    time1 = mins + "0" + secs + "0" + milsec; 
	
	time1 += Math.random().toString().substring(2,6);
	
    return time1;
 } 
 
var tempDbg = 1;

function getNewRowId(){
	newRowId = rowCounter;
	newRowId = newRowId + 1;
	rowCounter++;

	return newRowId;
}

function createNewParagraph(rowId, rowLevel, lastRow, dbLineId){

	if (dbLineId > -1){
		var newRowId = dbLineId;	
		var isNewLine = false;		
	}
	else {
		var newRowId = getNewRowId();
		var isNewLine = true;
	}
	
	if (!saveAllP==""){ saveAllP += "|"; }
	saveAllP += newRowId;		

	if (lastRow){
		var rowIndex = document.getElementById("budgetTr" + rowId).rowIndex;	
	}
	else {
		var rowIndex = document.getElementById("budgetTr" + rowId).rowIndex + 1;	
		}
	
	var myRow = $("#tblBudgetBody")[0].insertRow(rowIndex);
	myRow.id = "budgetTr" + newRowId;

	$("#" + myRow.id).attr('class', 'trBudgetP');

	var myCell = myRow.insertCell(-1);
	myCell.id = "tdControl" + newRowId;
	
	$('#tdControl' + newRowId).attr('class', 'td0_data');
	
	var html = "";
	html += "<div class='divAction'>";
	html += "<input type='hidden' id='trKids" + newRowId + "' >";
	html += "<input type='hidden' id='trType" + newRowId + "' value='" + TR_TYPE_PARAGRAPH + "' >";
	html += getRowIdInput(newRowId, dbLineId);
	if ( showSort()  ){
		html += "<a class='aCutP' id='aCut_" + newRowId + "' href='javascript:doCut(" + TR_TYPE_PARAGRAPH + "," +  newRowId + ")' tabindex='-1' >";
		html += "<img title='Move this line' class='imgMoveP' id='imgMove_" + newRowId + "' src='" + imgMoveSrc + "' width='11' height='11' border='0' ></a>";		
		//html += "&nbsp;";
		html += " ";
	}
	html += "<a href='javascript: deleteRow(" + newRowId + ");' tabindex='-1' >" + deleteImg + "</a>";
	html += "</div'>";
	myCell.innerHTML = html; 
	
	var myCell = myRow.insertCell(-1);
	myCell.id = "tdTitle" + newRowId;
	$('#tdTitle' + newRowId).attr('class', 'td1_data');
	html = "";
	for (var i = 1; i < rowLevel; i++) {
		html += getLevelSpace();
	}

	html += "<input type='text' id='inpRowTitle_" + newRowId + "' class='inpLineTitle'  value='" + enterNewTitle + "'/>";
	html += "&nbsp;&nbsp;";
	myCell.innerHTML = html; 
	$('#inpRowTitle_' + newRowId).css('font-weight', 'bold');
	$("#inpRowTitle_" + newRowId).change(function() {
		budgetIsChanged();
	});
	
	var fieldsCount = $("#fieldsCounter").val();
	
	var classCounter = 1;
	var tdClassName = "";
	var tdFieldName = "";
	var showSum = "";
	
	for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
		var fieldType = $("#fld_type_" + fieldId).val();
		tdFieldName = "tdValue" + fieldId + "_" + newRowId;

		var myCell = myRow.insertCell(-1);
		myCell.id = tdFieldName;
		
		if (classCounter==1){
			tdClassName = "td2_data";
			classCounter++;
		}
		else {
			tdClassName = "td3_data";
			classCounter = 1;
		}
		$('#' + tdFieldName).attr('class', tdClassName );
			
		showSum = $("#fld_sum_" + fieldId).val();
		if ( fieldType=="1" || fieldType=="2"  ){		
			if (showSum=="1") {
				
				var fieldWidth = $("#fld_final_width_" + fieldId).val();
				var inpFldPName = getInpFieldPName(fieldId, newRowId);		
				html = "<input id='" + inpFldPName + "' class='divValueP' value='0' READONLY style='display:none; width: " + fieldWidth + "px;' tabindex='-1' >";
				myCell.innerHTML = html; 

			}
		}
	}
	
	
	
	var lineParentId = newRowId;
	
	// new tr - create new P under & new Line
	var rowIndex = document.getElementById("budgetTr" + newRowId).rowIndex;
	var myRow = $("#tblBudgetBody")[0].insertRow(rowIndex + 1);

	var newLineTitle = newLinePrefix + lineParentId;
	myRow.id = "budgetTr" + newLineTitle;
	$("#" + myRow.id).attr('class', 'trNewLine');

	var myCell = myRow.insertCell(-1);
	myCell.id = "tdControl" + newLineTitle;
	
	html = "&nbsp;";
	myCell.innerHTML = html; 
	$('#tdControl' + newLineTitle).attr('class', 'td0_data');	
	//$('#tdControl' + newLineTitle).css('background', 'red');
	
	var myCell = myRow.insertCell(-1);
	myCell.id = "tdTitle" + newLineTitle;
	$('#tdTitle' + newLineTitle).attr('class', 'td1_data');
	
	
	html = "";
	for (var i = 1; i <= rowLevel; i++) {
		html += getLevelSpace();
	}

	var htmlNewLine = "";
	htmlNewLine = "<div class='divNewLineLink' >";
	htmlNewLine += "<a id='aNewPBottom' class='aNewLine' href='javascript:createNewLine(" + lineParentId + ",\"" + newLineTitle + "\"," + rowLevel + ",true ,true, -1);'  tabindex='-1' ><img class='imgNewLine' src='images/PLUS.png' border='0'  ></a>";
	htmlNewLine += "</div>";	
	html = "<input type='hidden' id='trAddNewLineFor" + lineParentId + "' value='" + newLineTitle  + "' >";
	html +=  htmlNewLine; 
	myCell.innerHTML = html; 
	
	classCounter = 1;
	for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
		if (classCounter==1){
			tdClassName = "td2_data";
			classCounter++;
		}
		else {
			tdClassName = "td3_data";
			classCounter = 1;
		}

		var myCell = myRow.insertCell(-1);
		myCell.id = "tdNewLine_" + fieldId + "_" + newLineTitle;
		$("#tdNewLine_" + fieldId + "_" + newLineTitle).attr('class', tdClassName);
		myCell.innerHTML = ""; 	
	}


	if (isNewLine){
		createNewLine(lineParentId,newLineTitle,rowLevel, true, false, -1);
		
	}
	else {
		
		var dbLineTitle = $('#spnTrTitle_' + newRowId).html();
		if ( (dbLineTitle.length > 0) && (dbLineTitle != enterNewTitle  ))   {
			dbLineTitle = myReplace(dbLineTitle, "\\" , ""); 
			$('#inpRowTitle_' + newRowId).val( dbLineTitle );
			$('#inpRowTitle_' + newRowId).css( "color", "black" );
		}
		
		for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
			showSum = $("#fld_sum_" + fieldId).val();
			if (showSum=="1") {

				var dbLineValue = parseBFloat( $('#spnTrCost_' + fieldId + '_' + newRowId).html() );
				var inpFldPName = getInpFieldPName(fieldId, newRowId);		
				if (isTracker()){ 
					dbLineValue = 0;
				}
				else {
					$('#' + inpFldPName).val( addCommas( dbLineValue ));
				}
				
				if ( dbLineValue!=0){
					$("#" + inpFldPName).show();
				}
				else{
					//alert(dbLineValue);
				}
			}		
		}
		
	}
	
	$(".budgetContainer").attr({ scrollTop: $(".budgetContainer").attr("scrollHeight") });
	
}

function createNewLine(parentId,rowId,rowLevel,before,scrollAfter, dbLineId){
	
	
	if (dbLineId > -1){
		var newRowId = dbLineId;	
		var isNewLine = false;		
	}
	else {
		var newRowId = getNewRowId();
		var isNewLine = true;
		budgetIsChanged();
	}
	
	if (!saveAllLines==""){ saveAllLines += "|"; }
	saveAllLines += newRowId;	

	var rowIndex = document.getElementById("budgetTr" + rowId).rowIndex;
	if (before){
		var myRow = $("#tblBudgetBody")[0].insertRow(rowIndex);
	
	}
	else {
		var myRow = $("#tblBudgetBody")[0].insertRow(rowIndex + 1);
	
	}
	myRow.id = "budgetTr" + newRowId;
	$("#" + myRow.id).attr('class', 'trBudgetLine');	

	var myCell = myRow.insertCell(-1);
	myCell.id = "tdControl" + newRowId;
	
	$('#tdControl' + newRowId).attr('class', 'td0_data');
	
	//control td
	var html = "";
	html += "<div class='divAction'>";
	html += "<input type='hidden' id='trType" + newRowId + "' value='" + TR_TYPE_LINE + "' >";
	html += "<input type='hidden' id='trChangeType_" + newRowId + "'  >";
	html += "<input type='hidden' id='trLineParent_" + newRowId + "' value='" + parentId + "' >";
	html += getRowIdInput(newRowId, dbLineId);
	if ( showSort()  ){
		html += "<a class='aCutLine' id='aCut_" + newRowId + "' href='javascript:doCut(" + TR_TYPE_LINE + "," +  newRowId + ")' tabindex='-1' >";
		html += "<img class='imgMoveLine' id='imgMove_" + newRowId + "' src='" + imgMoveSrc + "' width='11' height='11' border='0' title='Move this line'></a>";		
//		html += "&nbsp;";
		html += " ";
	}
	html += "<a href='javascript: deleteRow(" + newRowId + ");' tabindex='-1' >" + deleteImg + "</a>";
	html += "</div>";
	myCell.innerHTML = html; 
	
	var myCell = myRow.insertCell(-1);
	myCell.id = "tdTitle" + newRowId;
	$('#tdTitle' + newRowId).attr('class', 'td1_data');
	$('#tdTitle' + newRowId).css('white-space', 'nowrap');
	
	//update  parent kids value
	var currentKids = $('#trKids' + parentId).val();
	
	if (before){ currentKids += "|"; }
		
	currentKids += newRowId; 
	$('#trKids' + parentId).val(currentKids);
	
	//control title td
	html = "";
	for (var i = 1; i <= rowLevel; i++) {
		html += getLevelSpace();
	}

	
	
	html += "<input type='text' id='inpRowTitle_" + newRowId + "' class='inpLineTitle' value='" + enterNewTitle + "'/>";
	myCell.innerHTML = html; 
	$("#inpRowTitle_" + newRowId).change(function() {
		budgetIsChanged();
	});
	
	var fieldsCount = $("#fieldsCounter").val();
	
	var classCounter = 1;
	var tdClassName = "";
	var inpDefaultValue = "";
	var tdFieldName = "";
	var inpFieldName = "";
	var fieldType = "";
	
	for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
	
		var fieldType = $("#fld_type_" + fieldId).val();
		var fieldWidth = $("#fld_final_width_" + fieldId).val();
		var fieldBgcolor = $("#fld_bgcolor_" + fieldId).val();
		
		if (fieldType=="1" || fieldType=="2")
			inpDefaultValue = "0";
		else if (fieldType=="5" ){
			inpDefaultValue = "--";
		}
		else {
			inpDefaultValue = "";
		}
	
		if (classCounter==1){
			tdClassName = "td2_data";
			classCounter++;
		}
		else {
			tdClassName = "td3_data";
			classCounter = 1;
		}
		
		tdFieldName = "tdValue" + fieldId + "_" + newRowId;
	
		var myCell = myRow.insertCell(-1);
		myCell.id = tdFieldName;
		$('#' + tdFieldName).attr('class', tdClassName);
		
		
		if (fieldType=="0" || fieldType=="1" || fieldType=="2"  ){		
			inpFieldName = getInpFieldName(fieldId, newRowId);
			
			var inputStyle = "";
			
			
			if (IsNumeric(fieldWidth)) {
				inputStyle += "width:" +   fieldWidth + "px;";
			}
			if (fieldBgcolor.length > 1){
				inputStyle += "background:" +   fieldBgcolor + ";";			
			}
			if (inputStyle.length > 0){
				inputStyle += " style='" + inputStyle + "' ";
			}
			
			html = "";
			if ((isTracker()) && (fieldId != 8)){
 				html += "<input type='hidden' id='" + inpFieldName + "xxxnote' class='inpValue' value=''  />";
				html += "<a class='editLongText' id='" + inpFieldName + "xxxpen'  style='display: none;' title='Write a note, add more values...' href='javascript:editTrackerValue(" + fieldId + "," + newRowId + ");' ><img class='' src='images/editTrack.png' border='0' height='12' width='12' ></a>";
				//html += "<a class='editTrackerValues' id='" + inpFieldName + "xxxpen'  title='Write a note, add more values...' href='javascript:editTrackerValue(" + fieldId + "," + newRowId + ");' >i</a>";
			}
			html += "<input type='text' id='" + inpFieldName + "' class='inpValue' value='" + inpDefaultValue + "' " + inputStyle + " />";

			myCell.innerHTML = html; 	 
			
			if (fieldType=="0"){
				$("#" + inpFieldName).css("text-align", "left");
			}
			
					
			$("#" + inpFieldName).change(function() {

				var rowId = getItemRow( $(this).attr("id") );		
				var fieldId = getItemId( $(this).attr("id") );	
				
				
				var fieldType = $("#fld_type_" + fieldId).val();
				var fldFormula = $("#fld_formula_" + fieldId).val();
				
				if (fieldType=="1" || fieldType=="2" ){

					if (!IsNumeric( $(this).val() )){
						$(this).val("0");			
					}
				}

				calcLine(fieldId, rowId);
				
				budgetIsChanged();
				
				if (isTracker() ){
					saveTrackerValue( rowId, fieldId, $(this).val(), "", "", "" );
					 $(this).css("color","black");
					 
					showTrackerNote(fieldId, newRowId);
					
				}
			});
		}
		else if (fieldType=="3"){
			//handle dates
			
			/*
			inpFieldName = getInpFieldName(fieldId, newRowId);
			html = "<input type='hidden' id='" + inpFieldName + "' class='inpValue' value=''  />";
			
			html += "<select id='" + inpFieldName + "nnMonth' class='selectDateMonth' onchange='javascript:changeMonth(" + fieldId + "," +  newRowId + ");' >";
			html += "<option value='0' style='color: #708090;' >Month</option>";

			html += "<option value='1' >Jan</option>";
			html += "<option value='2' >Feb</option>";
			html += "<option value='3' >Mar</option>";
			html += "<option value='4' >Apr</option>";
			html += "<option value='5' >May</option>";
			html += "<option value='6' >Jun</option>";
			html += "<option value='7' >Jul</option>";
			html += "<option value='8' >Aug</option>";
			html += "<option value='9' >Sep</option>";
			html += "<option value='10' >Oct</option>";
			html += "<option value='11' >Nov</option>";
			html += "<option value='12' >Dec</option>";
			
			html += "</select>";
			html += " ";

			html += "<select id='" + inpFieldName + "nnDay' class='selectDateDay' onchange='javascript:changeDay(" + fieldId + "," +  newRowId + ");' >";
			html += "<option value='0' style='color: #708090;'>Day</option>";
			for (var dayCounter=1; dayCounter <= 31; dayCounter++) {	
				html += "<option value='" + dayCounter + "' >" + dayCounter + "</option>";			
			}
			html += "</select>";  
			html += " "; 
			html += "<input id='" + inpFieldName + "nnYear' class='inpDateYear' value='" + currentYear() + "' onchange='javascript:changeMonth(" + fieldId + "," +  newRowId + ");' />";
			
			*/
			inpFieldName = getInpFieldName(fieldId, newRowId);
			//var today = new Date()
			//var saveDate = today.getMonth() + "/" +  today.getDate() + "/" + today.getFullYear();
			html = "<div style='width:90px;' >";
			html += '<input class="inpDatePicker" name="' + inpFieldName + '"  id="' + inpFieldName + '" value="" size="10"  style="font-size:11px;"/>';			
			html += " <a  href='javascript:showTrackerDatePicker(\"" + inpFieldName + "\");'><img src='images/calendar.png' border='0' width='16' height='13' >";
			html += "</div>";
 
			myCell.innerHTML = html; 			
			$("#" + myCell.id).css("text-align", "center");
			implementDate(inpFieldName); 
			$("#" + inpFieldName).css("width", "65px");

			$("#" + inpFieldName).change(function() {
				budgetIsChanged();
			});
			
			$("#" + inpFieldName).focus(function() {
				if (!isDate( $(this).val() ) ){
					var today = new Date();
					var saveDate = (today.getMonth() + 1) + "/" +  today.getDate() + "/" + today.getFullYear();				
					$(this).val(saveDate);
				}
			});
			

		}
		else if (fieldType=="4"){
			//handle long text
			inpFieldName = getInpFieldName(fieldId, newRowId);
			html = "<input type='hidden' id='" + inpFieldName + "' class='inpValue' value=''  />";
			html += "<a class='editLongText' title='Open the text editor' href='javascript:editLongText(" + fieldId + "," + newRowId + ");' >Edit <img src='images/editIcon.png' border='0' height='12' width='8' ></a>";

			myCell.innerHTML = html; 			
			$("#" + myCell.id).css("text-align", "center");

			}
		else if (fieldType=="5"){
			//handle list
			var inputStyle = "font-size: 11px;";
			if (IsNumeric(fieldWidth)) {
				inputStyle += "width:" +   fieldWidth + "px;";
			}
			if (fieldBgcolor.length > 1){
				inputStyle += "background:" +   fieldBgcolor + ";";			
			}
			

			inpFieldName = getInpFieldName(fieldId, newRowId);
			html = "<select id='" + inpFieldName + "' style='" + inputStyle + "' >";
			
			var fldItems = $("#fld_items_" + fieldId).html();
			
			if (fldItems.length > 1){
			
				var arrItems = fldItems.split(ITEM_SEPERATE_1);

				for(var i2=0; i2 <arrItems.length; i2++) {
					var listItem = arrItems[i2];
					var arrItem = listItem.split(ITEM_SEPERATE_2);
					
					html += "<option value='"  + arrItem[0] + "' ";
					var fontColor = arrItem[2] ;
					if (fontColor.length > 1){
						html += " style='color: " + fontColor + ";' ";
					}
					html += " >";
					html += arrItem[1] ;
					html += "</option>";
				}			
			}
			html += "</select>";
			myCell.innerHTML = html; 			
			
			$("#" + inpFieldName).change(function() {
				//$(this).css("color", $(this).children("option:selected").css("color"));      
				budgetIsChanged();
			});
						
		
		}
		else if (fieldType=="6"){
			//handle link
			var inputStyle = "font-size: 11px;";
			if (IsNumeric(fieldWidth)) {
				inputStyle += "width:" +   fieldWidth + "px;";
			}
			if (fieldBgcolor.length > 1){
				inputStyle += "background:" +   fieldBgcolor + ";";			
			}			
			if (inputStyle.length > 0){
				inputStyle += " style='" + inputStyle + "' ";
			}

			var inpFieldName = getInpFieldName(fieldId, newRowId);
			var html = "<input type='text' id='" + inpFieldName + "' class='inpValue' value='" + inpDefaultValue + "' " + inputStyle + " title='Enter a valid url address' />";
			html += "<a id='"  + inpFieldName  + "Link' target='_blank' class='aFieldLink' href='' > <img src='images/azikim.png' border='0' title='Open the url adress'></a>";
			
			myCell.innerHTML = html; 	
			$("#" + inpFieldName).css("text-align", "left");
					
			$("#" + inpFieldName).change(function() {

				var rowId = getItemRow( $(this).attr("id") );		
				var fieldId = getItemId( $(this).attr("id") );					
				var inpFieldName = getInpFieldName(fieldId, rowId);
				
				var newHref =  $.trim( $(this).val() );
				if (newHref.length < 1){
					newHref = "blank";
				}
				
				if ( newHref.indexOf("http://") != 0){
					newHref = "http://" + newHref;
				}
					
				$("#" + inpFieldName + "Link").attr("href",  newHref);
				
				budgetIsChanged();
			});
			
		}
		

	}

	setNewPTitle();
	
	if (isNewLine){
		setColorSchemeValues();
		setDesignValues();
		 dismissCut();
		$("#inpRowTitle_" + newRowId).focus();
		
	}
	else {
		
		var dbLineTitle = $('#spnTrTitle_' + newRowId).html();
		if ( (dbLineTitle.length > 0) && (dbLineTitle != enterNewTitle  ))   {
			dbLineTitle = myReplace(dbLineTitle, "\\" , ""); 
			$('#inpRowTitle_' + newRowId).val( dbLineTitle );
			$('#inpRowTitle_' + newRowId).css( "color", "black" );
		}
		
		var chaneType = $('#spnTrChangeType_' + newRowId).html();

		for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
			var fieldType = $("#fld_type_" + fieldId).val();
			var inpFldName = getInpFieldName(fieldId, newRowId);		
			
			if (parseBFloat(chaneType)==fieldId){
				$(inpFldName).css("color",BGCOLOR_INPUT_CHANGED);			
			}
			

			if (fieldType=="1" || fieldType=="2"){
			
					var dbLineValue = parseBFloat( $('#spnTrCost_' + fieldId + '_' + newRowId).html() );
				//alert(dbLineValue  + "  " + "spnTrCost_" + fieldId + "_" + newRowId);
			}
			else {
				var dbLineValue =  $('#spnTrCost_' + fieldId + '_' + newRowId).html();
				dbLineValue = getHtmlEntity(dbLineValue);
				if (fieldType=="4"){
					dbLineValue = br2nl( dbLineValue);					
					dbLineValue = myReplace(dbLineValue, "\\" , "");
				}
			}
			
			if (fieldType==FTYPE_DATE){
				//setDateValue(fieldId, newRowId);
				//function myReplace(str, findStr, replaceStr){
				var date_final_value = myReplace(dbLineValue,"#","/");
				if (isDate(date_final_value)){
					$('#' + inpFldName).val( ( date_final_value ));
				}
				else {
					//$('#' + inpFldName).val("");
				}
				
			}
			else if (!isTracker()){ 
			
				$('#' + inpFldName).val( ( dbLineValue ));
			}
			if  (fieldType==FTYPE_LINK){
				$('#' + inpFldName).change();
			}
			

			if (fieldType==FTYPE_LIST){
			}
						
		}
	}
	
	//scroll down after adding new line 
	if (scrollAfter){
		$(".budgetContainer").animate({ scrollTop: "+=21px"}, 100);
	}
	
}

function getRowIdInput(rowId, dbLineId){
	//lastRowId spnTrKey_
	lastRowId++; 
	var rowKey = "";
	
	/*
	if ( $("#spnTrKey_" + dbLineId).html() != null){
		if ( $("#spnTrKey_" + dbLineId).html() != undefined){
			var rowKey = $("#spnTrKey_" + dbLineId).html();	
		}
	}
	*/
	if ( $("#spnTrKey_" + dbLineId).val() != null){
		if ( $("#spnTrKey_" + dbLineId).val() != undefined){
			var rowKey = $("#spnTrKey_" + dbLineId).val();	
		}
	}
	
	if (rowKey.length < 3){
		var time1 = get_time();		
		rowKey = time1 + "_" + lastRowId;		
	}
	var html = "<input type='hidden' id='rowKey_" + rowId + "' value='" + rowKey + "' >";	
	html += "<input type='hidden' id='rowIdByKey_" + rowKey + "' value='" + rowId + "' >";	
	return  html;	
}

function deleteRow(rowId){
	var trType = $("#trType" + rowId).val();
	
	if (trType==TR_TYPE_PARAGRAPH){
		var kids = $("#trKids" + rowId).val();
		var arrKids = kids.split("|");

		for(var i=0; i<arrKids.length; i++) {
			var value = arrKids[i];
			if (document.getElementById('budgetTr' + value)==null){
			}
			else {
				var rowIndex = document.getElementById("budgetTr" + value).rowIndex;		
				document.getElementById('tblBudgetBody').deleteRow(rowIndex);
			}
		}
		
		var addNewLine = $('#trAddNewLineFor' + rowId).val();
		var newLineIndex = document.getElementById("budgetTr" + addNewLine).rowIndex;		
		document.getElementById('tblBudgetBody').deleteRow(newLineIndex);	

	}
	else {
		var pId = $("#trLineParent_" + rowId).val();		
	}
	
	var rowIndex = document.getElementById("budgetTr" + rowId).rowIndex;		
	document.getElementById('tblBudgetBody').deleteRow(rowIndex);	
	
	if  (trType==TR_TYPE_LINE) {
		resetKids(pId);
		
	
	}
	
	if (trType==TR_TYPE_PARAGRAPH){
		calcTotal(false);
	}
	else {
		calcP(pId, true);	
	}
	
	budgetIsChanged();
	
	

}


function calcLine(changeType, rowId){
	$("#trChangeType_" + rowId).val(changeType);
	
	
	var fldFormula = $("#fld_formula_" + changeType).val();	
	doCalcFormula( fldFormula, changeType, rowId);

	var fldFormula = $("#fix_formula").val();	
	doCalcFormula( fldFormula, changeType, rowId);

	var pId = $("#trLineParent_" + rowId).val();
	calcP(pId, true);
}

function doCalcFormula(fldFormula, changeType, rowId){
	var arrFormula = fldFormula.split(";");

	for ( var i=0; i < (arrFormula.length - 1); i++) {
		var currentFormula = arrFormula[i];
		
		arrFieldInFormula = currentFormula.split("#");
		
		var affected = arrFieldInFormula[0];
		var firstItem = arrFieldInFormula[1];
		var actionId = arrFieldInFormula[2];
		var secondItem = arrFieldInFormula[3];

		
		var inpFieldName = getInpFieldIndex(firstItem, rowId);
		var firstValue = parseBFloat( $("#" + inpFieldName).val() );
		
		if (secondItem.indexOf("_") == 0){
			var pos1 = secondItem.indexOf("_");				
			secondItem = secondItem.substr( (pos1 + 1), (secondItem.length - (pos1 + 1)) );	
			inpFieldName = getInpFieldIndex(secondItem, rowId);
			var secondValue = parseBFloat( $("#" + inpFieldName).val() );			
		}	
		else if (secondItem=="i"){
			var secondValue = parseBFloat($("#inpItemCounter").val());		
		}
		else {
			var secondValue = parseBFloat( secondItem );		
		}
		
		var result = 0;
		if (actionId==1){
			result = firstValue + secondValue;
		}
		else if ( actionId==2){
			result = firstValue - secondValue;
		}
		else if ( actionId==3){
			result = firstValue * secondValue;
		}
		else if ( actionId==4){
			if (secondValue==0) 
				result = 0
			else
				result = firstValue / secondValue;
		}
		
		inpFieldName = getInpFieldIndex(affected, rowId);
		setInputAfterChange("#" + inpFieldName, result);

		if (!isTracker()){
			inpFieldName = getInpFieldName(changeType, rowId);
			$("#" + inpFieldName).css("color",BGCOLOR_INPUT_CHANGING);
		}
	}
	

}

function calcP(pId, isCalcTotal){
	var kids = $("#trKids" + pId).val();
	var arrKids = kids.split("|");
	var valueP = 0;
	var fieldName = "";
	
	var fieldsCount = $("#fieldsCounter").val();	
	for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
		
		valueP = 0;
		
		var showSum = $("#fld_sum_" + fieldId).val();
		if (showSum=="1"){
		
			for(var i=0; i<arrKids.length; i++) {
				var rowId = arrKids[i];
				if (document.getElementById('budgetTr' + rowId)==null){
				}
				else {
					fieldName = getInpFieldName(fieldId, rowId);
					valueP = valueP + parseFloat( $("#" + fieldName).val() );							
				}
			}	
			
	 		fieldName = getInpFieldPName( fieldId, pId);						
			$("#" + fieldName).val( addCommas( valueP.toFixed(1))  );			
			
			//alert(valueP);
			if (valueP==0){
				$("#" + fieldName).hide();
			}
			else {
				$("#" + fieldName).show();
			}
			//
		}
	}

	if (isCalcTotal){
		calcTotal(false);
	}
}

function calcTotal(reCalcP){
	var arrP = saveAllP.split("|");
	var valueTotal = 0;
	var valueCurrent = 0;
	var newValue = 0;
	var fieldName = "";

	var fieldsCount = $("#fieldsCounter").val();	
	for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
		var showSum = $("#fld_sum_" + fieldId).val();
		if (showSum=="1"){
			valueCurrent =  parseBFloat( $("#inpTotal_" + fieldId).val() )  ;
			$("#inpTotal_" + fieldId).val(0);
		}		
	}
		
	for(var i=0; i< arrP.length; i++) {

		var rowId = arrP[i];
		
		if (document.getElementById('budgetTr' + rowId)==null){
		}
		else {
			for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
				
				var showSum = $("#fld_sum_" + fieldId).val();
				if (showSum=="1"){
					if (reCalcP){
						calcP(rowId,false);
					}
					
					fieldName = getInpFieldPName( fieldId, rowId);			
					newValue = parseBFloat( $("#" + fieldName).val() )  ;
					valueCurrent =  parseBFloat( $("#inpTotal_" + fieldId).val() )  ;

					valueCurrent = valueCurrent + newValue;
					$("#inpTotal_" + fieldId).val(valueCurrent);
					
				}
			}
			
		}
	}

	for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
		var showSum = $("#fld_sum_" + fieldId).val();
		if (showSum=="1"){
			valueCurrent =  parseBFloat( $("#inpTotal_" + fieldId).val() )  ;
			$("#inpTotal_" + fieldId).val( addCommas( valueCurrent.toFixed(1)) );
		}		
	}
}

function reCalcLine(itemCounter){

	var arrL = saveAllLines.split("|");
	var changeType;
	
	for(var i=0; i< arrL.length; i++) {
		var rowId = arrL[i];
		if (document.getElementById('budgetTr' + rowId)==null){
		}
		else {
			
			changeType = $("#trChangeType_" + rowId).val();
			if (IsNumeric(changeType)){
				calcLine(changeType, rowId);			
			}
		}
	}	

}


function getLevelSpace(){
	//return "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	return "&nbsp;&nbsp;&nbsp;&nbsp;";
}


function getItemRow(strValue){
	var pos1 = strValue.indexOf("_");
	var result = "";
	if (pos1 > -1) {
		
		result = strValue.substr( (pos1 + 1), (strValue.length - (pos1 + 1)) );	
	}

	return result;
}  

function getItemId(strValue){
	var pos1 = strValue.indexOf("-");
	var pos2 = strValue.indexOf("_");
	var result = "";
	if (pos1 > -1) {
		
		result = strValue.substr( (pos1 + 1), (pos2 - (pos1 + 1)) );	
	}

	return result;
}


function saveCurrentBudget(createCopy) {
	var budgetUserId = $("#budgetUserId").val();
	
	
	if (userId==""){
		signUp(true);
	}
	else if  ((userId != budgetUserId) || (createCopy) ){
		showNewBudget();	
	}
	else {
		
		showSavingWindow("", 2100);
	    
		var budgetId = $("#budgetId").val();
		saveBudgetLines(budgetId, false);
		budgetIsSaved();
	}
	
}

function saveBudgetLines(budgetId, isNewBudgt){

	var dataString = "userId=" + userId;
	dataString += "&budgetId=" + budgetId;
	dataString += "&isTracker=" + $("#isTracker").val();
	

	if (!isNewBudgt){
		var budgetTitle = $("#divBudgetTitle").html();
		var newValue = br2nl( $("#divBudgetDesc").html() );  
		var budgetDesc = newValue;
		
		var tags = $("#tags").val();	
		var itemCounter = $("#inpItemCounter").val();			
		var selectedColor = $("#selectedColor").val();	
		var privacyId = $("#selectedPrivacyId").val();	
		var categoryId = $("#selectedCategoryId").val();	
		var permissionId  = $("#permissionId").val();	
		var tagStr  = $("#inpTagStr").val();	
		
		//if (userId == "15466"){
		//	alert(tagStr);
		//}
		
		dataString += "&budgetTitle=" + budgetTitle;
		dataString += "&budgetDesc=" + budgetDesc;	
		dataString += "&tags=" + tags;	
		dataString += "&itemCounter=" + itemCounter;	
		dataString += "&selectedColor=" + selectedColor;
		dataString += "&privacyId=" + privacyId;
		dataString += "&categoryId=" + categoryId;
		dataString += "&permissionId=" + permissionId;
		dataString += "&tagStr=" + tagStr;
		
		globalIsNewBudget = false;
	}
	else {
		dataString += "&newBudget=1";		
		globalIsNewBudget = true;
		globalValue = budgetId;
	}

	var rowsCounter = parseInt( $("#budgetRowsCounter").val() );	
	
	var rowTitle = ""; 
	var rowType = "";
	var saveRows = "";
	var rowCounter = 0;
	var rowId = -1;
	var strLngth = -1;
    $("#tblBudgetBody tr").each(function(t){
		
		if (this.id.indexOf('budgetTr') == 0) {
			
			strLngth = this.id.length - 8;			
			rowId = this.id.substr(8, strLngth);
			rowType = $("#trType" + rowId).val();	

			if (rowType!=undefined){
				if (saveRows!="") 
					{ saveRows += ' '; }
					
				saveRows += rowId;							
				
				dataString += "&rowTitle" + rowId + "=" + hSigns($("#inpRowTitle_" + rowId).val());
				dataString += "&rowType" + rowId + "=" + rowType;
				dataString += "&rowKey" + rowId + "=" + $("#rowKey_" + rowId).val();
				var fieldsCount = $("#fieldsCounter").val();	
				for (var fieldId=1; fieldId <= fieldsCount; fieldId++) {	
					var fieldType = $("#fld_type_" + fieldId).val();
					if (rowType==TR_TYPE_PARAGRAPH){
						fieldName = getInpFieldPName(fieldId, rowId);
						if (fieldType==1 || fieldType==2)
							dataString += "&valueField_" + fieldId + "_" + rowId + "=" + parseBFloat( $("#" + fieldName).val() );					
						else
							dataString += "&valueField_" + fieldId + "_" + rowId + "=" +  $("#" + fieldName).val() ;					
					}
					else if (rowType==TR_TYPE_LINE){
						fieldName = getInpFieldName(fieldId, rowId);
						if (fieldType==1 || fieldType==2)
							dataString += "&valueField_" + fieldId + "_" + rowId + "=" + parseBFloat( $("#" + fieldName).val() );					
						else
							dataString += "&valueField_" + fieldId + "_" + rowId + "=" +  $("#" + fieldName).val();
					}			
				
				}
			}
			
			
		
		
			rowCounter++;
		}
		
	});
	
	//do the line insert
	dataString += "&saveRows=" + saveRows;		
	
	if (isEmbed){
		dataString += "&isEmbed=true";
	}
	
	
	$.ajax({   
		type: "POST",   
		url: "newBudgetLine.php",   
		context: document.body,		
		data: dataString,   
		success: function(){  						
			
			if ((globalIsNewBudget) && (!isEmbed)){
				document.location.href = "?sheetId=" + globalValue;
			}
			else {
				budgetIsSaved();
			}
		
		}
	});
	
	
}


function showNewBudget(){
	var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Save New Spreadsheet</span><br><br>";
	html += "<table id='tblSignUp' bgcolor='gainsboro' style='padding:5px; font-size:14px; line-height: 18px; border: 1px solid #708090;' >";

	html += "<tr><td><b>Title</b></td></tr>";	
	html += "<tr><td nowrap><input type='text' id='newTitle' style='width: 240px;'  ></td></tr>";	
	html += "<tr><td nowrap style='color: #708090;' >The title should say what's the spreadsheet is about<br></td></tr>";	
	html += "<tr><td nowrap><br></td></tr>";	

	html += "<tr><td><b>Description</b></td></tr>";	
	html += "<tr><td nowrap><textarea id='newDesc' rows='3' cols='60'></textarea></td></tr>";	
	html += "<tr><td nowrap><br></td></tr>";	
		
	html += "<tr><td><br><b>Privacy </b> ";
	html += "<select id='privacyId'>";
	html += "<option value='2'>Private</option>"
	html += "<option value='1'>Public</option>"
	html += "</select>";
	html += "<br><br></td></tr>";		
	
	html += "</table><br>";	
	html += "<span id='windowMsg' style='color:red; padding: 3px;'></span>";
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitBudget' />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideWindow' />";	
	html += "<br><br><br>";		
	
	document.getElementById("registerInner").innerHTML = html;
	
	$('.inpNewBudget').css('width', '200px;');
	$('#submitBudget').css('color', 'green');
	$('#submitBudget').css('font-weight', 'bold');

	$("#submitBudget").click(function(event) {   
		
		createNewBudget(); 
		event.preventDefault();
	});   

	$("#hideWindow").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$('#registerContent').animate({		
		width:  '530px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 
	$("#windowMsg").hide();


}

function createNewBudget(){
	var newTitle = $("#newTitle").val();
	var newDesc = $("#newDesc").val();
//	var newTags = $("#newTags").val();
	
	if (newTitle.length < 5){		
		$("#windowMsg").fadeIn(1000);
		$("#windowMsg").html('<b>Your budget title is too short</b><br><br>');
	
	}
	else if (newTitle.length > 50){		
		$("#windowMsg").fadeIn(1000);
		$("#windowMsg").html('<b>Your budget title is too long</b><br><br>');
	
	}
	else {
		$("#submitBudget").attr('disabled', 'disabled'); 
		
		var dataString = "";
		var budgetTempId = get_time() + "_" + userId;			
		

		dataString = "userId=" + userId;
		dataString += "&budgetTitle=" + newTitle;
		dataString += "&budgetDesc=" + newDesc;
//		dataString += "&tags=" + newTags;
		dataString += "&budgetUserId=" + $("#budgetUserId").val();
		dataString += "&budgetId=" + $("#budgetId").val();
		dataString += "&budgetTempId=" + budgetTempId;
		dataString += "&budgetCategoryId=" +  $("#budgetCategoryId").val();		
		dataString += "&valueField=" + parseFloat($("#inpItemCounter").val());
		dataString += "&selectedColor=" + $("#selectedColor").val();
		dataString += "&privacyId=" + $("#privacyId").val();
		dataString += "&t1=" + get_time();
				
		globalValue = budgetTempId;
		
		$.ajax({   
			type: "POST",   
			url: "newBudget.php",   
			context: document.body,
			data: dataString,   
			success: function(){  						
						
					saveBudgetLines( globalValue, true);					
				
			}
		});
	
	}

}

function isMyBudget(){
	if (budgetUserId == userId )	
		return true;
	else
		return false;
}


function budgetIsChanged(){
	if (!isCreatingFromDb){
		if (isEmbed){				
			saveValuesEmbed();
		}
		else {
			$(".imgBtnSave").attr("src","images/blue/blueSave.png?" + Math.random());
			$(".imgBtnSave").attr("title","Save Changes");
		}
	}
	dismissCut();
}


function budgetIsSaved(){
	$(".imgBtnSave").attr("src","images/SAVE.png?" + Math.random());

}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function removeCommas(newValue)  {
	return parseFloat(  newValue.replace(/,/g , "") );
}

function parseBFloat(newValue)  {
	if (newValue==undefined){
		return parseFloat(newValue);
	}
	else if (newValue.length == 0){
		return "0";
	}
	else {
		return parseFloat(  newValue.replace(/,/g,"") );
	}
}

function setInputAfterChange(inputName, inputValue){
	var strNewValue = inputValue.toString();
	if (strNewValue.indexOf(".") > 0){
		strNewValue = inputValue.toFixed(2);
	}
	$(inputName).val(strNewValue);
	$(inputName).css("color",BGCOLOR_INPUT_CHANGED);


}

function setColorSchemeValues(){
	var selectedColor = $('#selectedColor').val();
	
	if (selectedColor.length < 2){
		selectedColor = "green";
	}
	
	if (selectedColor=="green")
		selectGreen();
	else if (selectedColor=="blue")
		selectBlue();
	else if (selectedColor=="red")
		selectRed();
	else if (selectedColor=="yellow")
		selectYellow();
}

function imposeMaxLength(Object, MaxLen){

  return (Object.value.length <= MaxLen);
}


function nl2br(text){
	text = escape(text);
	if(text.indexOf('%0D%0A') > -1){
		var re_nlchar = /%0D%0A/g ;
	}else if(text.indexOf('%0A') > -1){
		var re_nlchar = /%0A/g ;
	}else if(text.indexOf('%0D') > -1){
		var re_nlchar = /%0D/g ;
	}
	return unescape( text.replace(re_nlchar,'<br>') );
}

function removeNl(text){
	text = escape(text);
	if(text.indexOf('%0D%0A') > -1){
		var re_nlchar = /%0D%0A/g ;
	}else if(text.indexOf('%0A') > -1){
		var re_nlchar = /%0A/g ;
	}else if(text.indexOf('%0D') > -1){
		var re_nlchar = /%0D/g ;
	}
	return unescape( text.replace(re_nlchar,'') );

}

function br2nl(text){
	var resultStr = removeNl(text);
	var resultStr = myReplace(resultStr, "<BR>", "<br>");
	
	//var re_nlchar = /<BR>/g ;
	//resultStr =  unescape(text.replace(re_nlchar,'%0D%0A')) ;
	
	var re_nlchar = /<br>/g ;
	//resultStr = unescape( resultStr.replace(re_nlchar,'%0D%0A')) ;
	resultStr = myReplace(resultStr, "<br>", "\n")
	
	return resultStr;
	
	//return text.replace(/<br\s*\/?>/mg,"\n\r");

}

function nl2nl(text){
	var re_nlchar = /\\n/g ;
	return unescape( text.replace(re_nlchar,'%0D%0A') );

}


function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		cntfield.value = maxlimit - field.value.length;
}


function commentTextCounter(field,maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	else
		document.getElementById("remLen1").value = maxlimit - field.value.length;
}


function postComment(sheetId){
	if (IsNumeric(userId)){
		var dataString = "";

		dataString = "userId=" + userId;
		dataString += "&budgetId=" + sheetId;
		dataString += "&content=" + $("#txtNewComment").val();

		
		$.ajax({   
			type: "POST",   
			url: "newComment.php",   
			context: document.body,
			data: dataString,   
			success: function(){  						
				
				showSavingWindow("Saving Comment...", 2500);
			}
		});		
	}
	else {
		
		showLogin(false, false);
	}
}

function deleteBudget(deleteBudgetId){
	$('html, body').animate({scrollTop:0}, 'fast'); 
	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;
	var html = "";
	html += "<span class='smallWindowTitle'>Remove Sheet</span><br><br>";
	html += "This action will completely remove <br><br>";
	html += "<div style='width: 320px; padding-bottom: 14px; font-size: 14px; font-weight: bold; '>";
	html += "" + $('#aDashBudget_' + deleteBudgetId).html() + " <br><br>";
	html += "<div style='text-align: center; padding-top: 20px;'>";
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitDelete' />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideSignUp' />";	
	html += "</div>";
	document.getElementById("registerInner").innerHTML = html;		
	
	$('#registerContent').animate({		
		width:  '380px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 
	
	$('#submitSignUp').css('color', 'green');
	$('#submitSignUp').css('font-weight', 'bold');
	
	globalValue = deleteBudgetId;
	$("#submitDelete").click(function(event) {   
		doDeleteBudget(globalValue); 
		event.preventDefault();
	});   
	
	$("#hideSignUp").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
}

function doDeleteBudget(budgetId){
	dataString = "budgetId=" + budgetId;
	$.ajax({   
		type: "POST",   
		url: "removeBudget.php",   
		context: document.body,
		data: dataString,   
		success: function(){  						
			location.reload();
			
		}
	});
	
}

function changeNickname(){
	var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Change Settings</span><br><br>";
	html += "<table id='tblSignUp' bgcolor='gainsboro' style='padding:5px; font-size:14px; line-height: 18px; border: 1px solid #708090;' >";

	html += "<tr><td><b>Edit Nickname</b></td></tr>";	
	html += "<tr><td nowrap><input type='text' id='newNickname' style='width: 200px;' value='" + userNickname + "'  ></td></tr>";	
	//html += "<tr><td nowrap style='color: #708090;' >The title should say what's the budget about<br></td></tr>";	
	html += "<tr><td nowrap><br></td></tr>";	

	html += "</table><br>";	
	html += "<span id='nicknameMsg' style='color:red; padding: 3px;'></span><br><br>";
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitForm' />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideWindow' />";	
	html += "<br><br><br>";		
	
	document.getElementById("registerInner").innerHTML = html;
	
	$('.inpNewBudget').css('width', '200px;');
	$('#submitBudget').css('color', 'green');
	$('#submitBudget').css('font-weight', 'bold');

	$("#submitForm").click(function(event) {   
		doChangeNickname(); 
		event.preventDefault();
	});   
	
	$("#hideWindow").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$('#registerContent').animate({		
		width:  '330px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 
	$("#windowMsg").hide();

}

function doChangeNickname(){
	
	document.getElementById("nicknameMsg").innerHTML = "";
	var newNickname = $("#newNickname").val();
	
	if (newNickname.length < MIN_NICKNAME){
		document.getElementById("nicknameMsg").innerHTML = "Please enter your nickname - " + MIN_NICKNAME + " characters or more";
	}
	else {
		dataString = "userId=" + userId;
		dataString += "&action=1";
		dataString += "&newNickname=" + $("#newNickname").val();

		
		$.ajax({   
			type: "POST",   
			url: "updateUser.php",   
			context: document.body,
			data: dataString,   
			success: function(){  						
				
				$("#spnNicknameDash").html( $("#newNickname").val() );
				showSavingWindow("Saving nickname...", 2500);
			}
		});		
	}
	
}

function changePassword(){
	var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Change Your Password</span><br><br>";
	html += "<table id='tblSignUp' bgcolor='gainsboro' style='padding:5px; font-size:14px; line-height: 24px; border: 1px solid #708090;' >";

	//html += "<tr><td><b>Edit Nickname</b></td></tr>";	
	html += "<tr><td class='tdPassHdr' id='tdPassOld' >Old Password</td><td nowrap><input type='password' id='oldPass' style='width: 200px;' value=''  ></td></tr>";	
	html += "<tr><td class='tdPassHdr'  id='tdPassNew'>New Password</td><td nowrap><input type='password' id='newPass' style='width: 200px;' value=''  ></td></tr>";	
	html += "<tr><td class='tdPassHdr' id='tdPassRe' >Confirm Password</td><td nowrap><input type='password' id='confirmPass' style='width: 200px;' value=''  ></td></tr>";	
	html += "<tr><td nowrap><br></td></tr>";	

	html += "</table><br>";	
	html += "<span id='passMsg' style='color:red; padding: 3px; font-weight: bold;'></span><br><br>";
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitForm' />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideWindow' />";	
	html += "<br><br><br>";		
	
	document.getElementById("registerInner").innerHTML = html;
	
	$('.inpNewBudget').css('width', '200px;');
	$('#submitBudget').css('color', 'green');
	$('#submitBudget').css('font-weight', 'bold');

	$("#submitForm").click(function(event) {   
		doChangePass(); 
		event.preventDefault();
	});   
	
	$("#hideWindow").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$('#registerContent').animate({		
		width:  '370px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 
	$("#windowMsg").hide();

}

function doChangePass(){
	
	$("#tdPassOld").css("color","black");
	$("#tdPassNew").css("color","black");
	$("#tdPassRe").css("color","black");
	
	document.getElementById("passMsg").innerHTML = "";
	var oldPass = $("#oldPass").val();

	var time1 = get_time();		
	$.get("login.php?user_email=" + userEmail + "&user_password=" + oldPass + "&checkPass=1&t=" + time1, function(data) {
		
		if (isLoginLegal(data)){	
			var newPass = $.trim( $("#newPass").val() );
			var rePass = $("#confirmPass").val();
			
			if (newPass.length < 6){
				$("#passMsg").html("Password must be 6 characters or more");
				$("#tdPassNew").css("color","red");
			}
			else if (newPass != rePass){
				$("#passMsg").html("Re-Password don't match");
				$("#tdPassRe").css("color","red");
			}
			else {
				dataString = "userId=" + userId;
				dataString += "&action=2";
				dataString += "&newPass=" + $("#newPass").val();
				
				$.ajax({   
					type: "POST",   
					url: "updateUser.php",   
					context: document.body,
					data: dataString,   
					success: function(){  						
						
						showSavingWindow("Saving password...", 2500);
					}
				});		
			}
		}
		else {
			$("#passMsg").html("Old password don't much");
			$("#tdPassOld").css("color","red");
		}
	});
	
}

function forgetPass(){
	var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Re-send Password</span><br><br>";
	html += "<table id='tblSignUp' bgcolor='gainsboro' style='padding:5px; font-size:13px; line-height: 24px; border: 1px solid #708090;' >";

	html += "<tr><td><b>Email </b></td>";	
	html += "<td nowrap><input type='text' id='newEmail' class='inputSingUp' ></td>";	
	html += "</tr>";	

	html += "<tr><td colspan='4' align='center' ><b><span id='emailMsg' style='color:red; padding: 3px;'></span></b></td></tr>";

	html += "</table><br>";	
	html += "<input type='button' class='inpButton' value=' Continue '  id='submitLogin'  />";	
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Cancel ' id='hideLogin' />";	
	html += "<br>";		

	document.getElementById("registerInner").innerHTML = html;
	
	$('#inpButton').attr("disabled", true); 
	$('#submitLogin').css('color', 'green');
	$('#submitLogin').css('font-weight', 'bold');

	$("#submitLogin").click(function(event) {   
		checkEmailAddress( $('#newEmail').val() );
		event.preventDefault();
	});   
	
	$("#hideLogin").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$("#newEmail").change(function() {   
	});   


	$('#registerContent').animate({		
		width:  '340px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast");
	$("#passMsg").hide();
	$('html, body').animate({scrollTop:0}, 'fast');  

}

function checkEmailAddress(newEmail){
	$('#inpButton').attr("disabled", true); 

	validEmail = 0;
	var time1 = get_time();	
	$.get("checkEmail.php?emailAddress=" + newEmail + "&t=" + time1, function(data) {
	
		validEmail=data;
		if (validEmail=="3"){
			//document.getElementById("emailMsg").innerHTML = "The email address is already registered to calculito";
			sendPass( $('#newEmail').val() );
			
			
		} 
		else {
			document.getElementById("emailMsg").innerHTML = "The email address not exists";
			
		}
	});

}

function sendPass(emilAddress){
	var time1 = get_time();	
	$.get("sendPass.php?emailAddress=" + emilAddress + "&t=" + time1, function(data) {
		showSavingWindow("Sending Password", 8000);		
		
	});

}

function showSavingWindow(windowMsg, fadingTime){
	if (windowMsg==""){
		windowMsg = "Saving...";
	}

	var html = "";
	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;
	html += "<span class='smallWindowTitle'><br><br><br>" + windowMsg + "<br><br>";
	document.getElementById("registerInner").innerHTML = html;		
	
	$('#registerContent').animate({		
		width:  '200px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 
	$("#registerWindow").hide(fadingTime);
	$("#registerContent").hide(fadingTime); 		
	$("#txtNewComment").val("");
}

function getInpFieldName(fieldId, rowId){
	return  "inpFld-" + fieldId + "_" + rowId;
}

function getInpFieldIndex(fieldId, rowId){
	var fieldIndex = $("#fld_index_" + fieldId).val();
	return  "inpFld-" + fieldIndex + "_" + rowId;
}

function getInpFieldPName(fieldId, rowId){
	return  "inpFldP-" + fieldId + "_" + rowId;
}


var isFullscreen = false;
var saveTdRight = "";
function showFullscreen(){
	if (!isFullscreen){
		saveTdRight = $("#tdRightSide").html();
		$("#tdRightSide").html("");
		$("#tdRightSide").css("width", "1px");
		$("#tdLeftSide").css("width", "999px");
		if ($("#isTracker").val() == "true"){
			$(".budgetContainer").css("width", "835px");
		}
		else {
			$(".budgetContainer").css("width", "923px"); 
		
		}
		$(".budgetContainer").css("height", "420px");
		$(".imgFullscreen").attr("src", "images/small_screen.png?" + Math.random());
		$(".trackerContainer").css("width", "800px");

		isFullscreen = true;
	}  
	else {
		$("#tdRightSide").html(saveTdRight);
		$("#tdLeftSide").css("width", "700px");
		$("#tdRightSide").css("width", "299px");
		$("#tdRightSide").css("padding-left", "20px"); 
		
		$(".imgFullscreen").attr("src", "images/big_screen.png?" + Math.random());
		$(".trackerContainer").css("width", "600px");
		isFullscreen = false;	
	
		setSheetWidth();
	}

}

function setSheetWidth(){
	var divWidth = getSheetWidth();
	
	$(".budgetContainer").css("width", divWidth + "px");
	$(".budgetContainer").css("height", "350px");
}

function getSheetWidth(){
	var tblWidth = document.getElementById("tblBudget").offsetWidth ;
	var divWidth = 618; 
	if (tblWidth < 604) {
		divWidth = (tblWidth + 21);
	}
	return divWidth;
}



function showEmbed(sheetId){

	var html = "";
	var divWidth = getSheetWidth() + 10;
	

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Add this spreadsheet to your website</span><br><br>";
	html += "<table id='tblEmbed' bgcolor='gainsboro' style='padding:5px; font-size:13px; line-height: 24px; border: 1px solid #708090;' >";

	html += "<tr><td>Copy and paste the embed code</td>";	
	html += "</tr>";	

	html += "<tr><td><textarea id='txtEmbedSheet' rows='5' cols='90' readonly >";
	
	textValue = "<iframe ";
	textValue += " height='430' ";		
	textValue += " width='" + divWidth + "' ";		
	textValue += " frameborder='0' scrolling='no' <BR>";		
	textValue += " src='http://www.calculito.com?sheetId=" + sheetId + "&embed=true' ><BR>";		
	
	html += br2nl(textValue);	
	html += "</iframe>";
	
	html += "</textarea></td></tr>";
	html += "</table>";	
	html += "<br>";		
	html += "<input type='button' class='inpButton' value=' Close ' id='hideLogin' />";	
	html += "<br>";		

	document.getElementById("registerInner").innerHTML = html;
	
	$('#inpButton').attr("disabled", true); 
	
	$("#hideLogin").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$("#txtEmbedSheet").focus(function(){     
			this.select(); 
	});

	

	$('#registerContent').animate({		
		width:  '490px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast");
	$("#passMsg").hide();
	$('html, body').animate({scrollTop:0}, 'fast');  

}

function saveValuesEmbed(){
	var sheetId = $("#budgetId").val();
	saveBudgetLines(sheetId, true);
}

function hSigns(str){

	/*
	if (text.indexOf('&') > -1){
		var replaceValue = /aa/g ;
		return ( text.replace(replaceValue,'_clcSign1_') );
	}
	else if (text.indexOf('+') > -1) {
		var replaceValue = /+/g ;
		return ( text.replace(replaceValue,'_clcSign2_') );
	}
	else if (text.indexOf('\\') > -1)
	{	
		var replaceValue = /\\/g ;
		return ( text.replace(replaceValue, '_clcSign3_') );
	}
	else {
		return (text);
	}
	*/
	var text = encodeURIComponent(str);
	var replaceValue = /%26/g ;  //&
	text = text.replace(replaceValue,'_clcSign1_') ;
	var replaceValue = /%2B/g ;  //+
	text = text.replace(replaceValue,'_clcSign2_') ;
	var replaceValue = /%5C/g ;  // \
	text = text.replace(replaceValue,'_clcSign3_') ;
	var replaceValue = /%3C/g ;  // \
	text = text.replace(replaceValue,'') ;
	var replaceValue = /%3E/g ;  // \
	text = text.replace(replaceValue,'') ;
	return text;

}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function editLongText(fieldId, rowId){
	
	if (isEmbed){
		alert("Text cannot be edited when the sheet is embed");
	}
	else {
	
		var html = "";

		document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

		html += "<span class='smallWindowTitle'>Edit Text</span><br><br>";
		html += "<textarea id='txtLongText' rows='14' cols='75' onkeypress='return imposeMaxLength(this, 1000);' style='overflow: visible;' >";
		
		html += "</textarea>";
		html += "<br><br>";			
		
		html += "<input type='button' class='inpButton' value=' Save Changes '  id='submitText'  />";	
		html += " &nbsp;&nbsp; ";	
		html += "<input type='button' class='inpButton' value=' Cancel ' id='hideTextEditor' />";	
		html += "<br>";		
		html += "<input type='hidden'  value='" + rowId + "' id='longTextRow' >";	
		html += "<input type='hidden'  value='" + fieldId + "' id='longTextField' >";	

		document.getElementById("registerInner").innerHTML = html;
		
		$('#inpButton').attr("disabled", true); 
		$('#submitText').css('color', 'green');
		$('#submitText').css('font-weight', 'bold');

		var inpFieldName = getInpFieldName(fieldId, rowId);
		if (isTracker()){
			var textValue = $("#" + inpFieldName + "xxxnote").val();	
			if (textValue=="0")
				textValue = "";
		}
		else{
			var textValue = $("#" + inpFieldName).val();
		}
		
		textValue = myReplace(textValue,"<br>", "");
		textValue = getHtmlEntity(textValue);
		$("#txtLongText").val( textValue );
		
		
		$("#submitText").click(function(event) {   
			var fieldId = $("#longTextField").val();
			var rowId = $("#longTextRow").val();
			var inpFieldName = getInpFieldName(fieldId, rowId);

			$("#" + inpFieldName).val( $("#txtLongText" ).val( )  );
			budgetIsChanged();

			hidwWindow();
			event.preventDefault();
		});   
		
		$("#hideTextEditor").click(function(event) {   
			hidwWindow();
			event.preventDefault();
		});   
		

		$('#registerContent').animate({		
			width:  '445px'
		});

		$("#registerWindow").show();
		$("#registerContent").fadeIn("fast");
		$("#passMsg").hide();
		$('html, body').animate({scrollTop:0}, 'fast');  
	}
	
	

}

function editTrackerValue(fieldId,rowId){
	if (isEmbed){
		alert("Text cannot be edited when the sheet is embed");
	}
	else {
	
		var html = "";

		document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

//		var inpFieldName = getInpFieldName(fieldId, rowId);
//		alert( $("#" + inpFieldName).val() );
		
		var time1 = get_time();			
		var fieldName = getInpFieldName(fieldId, rowId);
		var trackerDate = arrTrackerDates[fieldId - 1];
		var sheetRowId = $("#rowKey_" + rowId).val();		
		var url_address = "getTrackerValues.php?trackerDate=" + trackerDate + "&sheetTempId=" + $("#sheetTempId").val() + "&lineId=" + sheetRowId + "&t=" + time1;
		
		
		$.get(url_address, function(data) {
			var line_title = $("#inpRowTitle_" + rowId).val();
			var arr_date = trackerDate.split("_");
			var date_name = arr_date[1] + " " + getMonthName(arr_date[0]) + " " + arr_date[2];
		
			html += "<span class='smallWindowTitle'>" + line_title +  " &nbsp;&nbsp;<font color='#707070'>" + date_name + "</font></span><br><br>";
			html += "<div style='border: 1px solid #707070; background: gainsboro; padding: 8px; width: 350px;' >";
			html += "<input type='hidden' id='inpTrkEditDate' value='" + trackerDate + "' >";
			html += "<input type='hidden' id='inpTrkEditFieldId' value='" + fieldId + "' >";
			html += "<input type='hidden' id='inpTrkEditRowId' value='" + sheetRowId + "' >";
			html += "<table id='tblTrackerSmall' name='tblTrackerSmall' ><tbody>";
			html += "<tr>";
			html += "<th>Amount</th>";
			html += "<th>Notes</th>";
			html += "<th></th>";
			html += "</tr>";
			var line_counter = 0;
			if (data!=undefined){
				
				arrTrackerValue = data.split(ITEM_SEPERATE_1);
				for(var i1=0; i1 <arrTrackerValue.length; i1++) {
					var dayValues = arrTrackerValue[i1];
					arrValues = dayValues.split(ITEM_SEPERATE_2);
					
					var trackerValue = arrValues[1];
					var trackerNote = arrValues[2];
					if (trackerNote == "0")
						trackerNote = "";
					
					if (trackerValue.indexOf(".") > 0){
						var floatValue = parseFloat(trackerValue);
						trackerValue = floatValue.toFixed(2);
					}
					
					if (parseFloat(trackerValue) > 0.001){
						var time1 = get_time();			
						html += "<tr id='tr" + time1 + "' >";
						html += "<td><input type='text' id='inpTrkValue" + time1 + "' class='inpTrackerValueSmall' value='" + trackerValue + "' ></td>";		
						html += "<td><input type='text' id='inpTrkNote" + time1 + "' class='inpTrackerNoteSmall'  value='" + trackerNote + "' ></td>";		
						html += "<td><a class='aDropTracker' href='javascript:dropTrackerLine(\"tr" + time1 + "\");' >Drop</a></td>";		
						html += "</tr>";
						 
						line_counter++;
					}					
				}
				
			}
			
			html += "</tbody></table>";
			html += "<br>";			
			html += "&nbsp; <a class='aCreateTracker' href='javascript:createNewTrackerLine();'  >Create new value</a>";		
			html += "<br><br></div>";			
			html += "<br><br><br>";			
			
			html += "<input type='button' class='inpButton' value=' Save Changes '  id='submitText'  />";	
			html += " &nbsp;&nbsp; ";	
			html += "<input type='button' class='inpButton' value=' Cancel ' id='hideTextEditor' />";	
			html += "<br>";		
			html += "<input type='hidden'  value='" + rowId + "' id='longTextRow' >";	
			html += "<input type='hidden'  value='" + fieldId + "' id='longTextField' >";	

			document.getElementById("registerInner").innerHTML = html;
			
			$('#inpButton').attr("disabled", true); 
			$('#submitText').css('color', 'green');
			$('#submitText').css('font-weight', 'bold');

			var inpFieldName = getInpFieldName(fieldId, rowId);
			
			//textValue = myReplace(textValue,"<br>", "");
			//textValue = getHtmlEntity(textValue);
			//$("#txtLongText").val( textValue );
			
			$(".inpTrackerValueSmall").change(function() {

				if (!IsNumeric( $(this).val() )){
					$(this).val("0");			
				}
			});
			
			$("#submitText").click(function(event) {   
				var fieldId = $("#longTextField").val();
				var rowId = $("#longTextRow").val();
				
				saveMultiTrackerValue(rowId, fieldId);
				budgetIsChanged();

				//hidwWindowFast();
				event.preventDefault();
			});   
			
			$("#hideTextEditor").click(function(event) {   
				hidwWindow();
				event.preventDefault();
			});   
			

			
		});
		

		$('#registerContent').animate({		
			width:  '445px'
		});

		$("#registerWindow").show();
		$("#registerContent").fadeIn("fast");
		$("#passMsg").hide();
		$('html, body').animate({scrollTop:0}, 'fast');  
	}
	

}

function dropTrackerLine(lineId){
	/*
	var t = document.getElementById(lineId);	
	var trId  = t.parentNode.id;
	var rowIndex = document.getElementById(trId).rowIndex;
	document.getElementById("tblTrackerSmall").deleteRow(rowIndex);	
*/
	var rowIndex = null;
    var rows = document.getElementById('tblTrackerSmall').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
		//alert(rows[i].id);
		if (rows[i].id ==lineId){
			
            rowIndex = rows[i].rowIndex;
        }
    }
	if (rowIndex != null)
		document.getElementById("tblTrackerSmall").deleteRow(rowIndex);	
}

function createNewTrackerLine(){
	var lineId = get_time();			
	
	var parent = document.getElementById("tblTrackerSmall");		
	var rowCount = parent.getElementsByTagName("tr").length;
	var myRow = $("#tblTrackerSmall")[0].insertRow(rowCount);
	
	myRow.id = "tr" + lineId;	

	var html = "";
	
	html += "<td><input type='text'  id='inpTrkValue" + lineId + "' class='inpTrackerValueSmall' value='0' ></td>";		
	html += "<td><input type='text'  id='inpTrkNote" + lineId + "' class='inpTrackerNoteSmall'  value='' ></td>";		
	html += "<td><a class='aDropTracker' href='javascript:dropTrackerLine(\"tr" + lineId + "\");' >Drop</a></td>";		

	$("#" + myRow.id ).html(html);			
	$(".inpTrackerValueSmall").change(function() {

		if (!IsNumeric( $(this).val() )){
			$(this).val("0");			
		}
	});
	
}

function myReplace(str, findStr, replaceStr){
	var arr = str.split(findStr);
	return arr.join(replaceStr);
}

function changeDay(fieldId, rowId){
	setYearValue(fieldId, rowId);
	saveDate(fieldId, rowId);
}

function changeMonth(fieldId, rowId){
	setYearValue(fieldId, rowId);
	saveDate(fieldId, rowId);
}

function setYearValue(fieldId, rowId){
	var inpFieldName = getInpFieldName(fieldId, rowId);
	var  yearValue = $("#" + inpFieldName  + "nnYear").val();
	if   (!IsNumeric(yearValue)) {
		$("#" + inpFieldName  + "nnYear").val(currentYear);
	}

}

function changeYear(fieldId, rowId){
	setYearValue(fieldId, rowId);
	saveDate(fieldId, rowId);
}

function currentYear(){
	var d = new Date();

	return  d.getFullYear();;
}

function saveDate(fieldId, rowId){
	var inpFieldName = getInpFieldName(fieldId, rowId);
	
	var finalDate =  $("#" + inpFieldName  + "nnDay").val() + "#";
	finalDate +=  $("#" + inpFieldName  + "nnMonth").val() + "#";
	finalDate +=  $("#" + inpFieldName  + "nnYear").val();
	
	$("#" + inpFieldName).val(finalDate);
	budgetIsChanged();
}

function setDateValue(fieldId, rowId){
	var inpFieldName = getInpFieldName(fieldId, rowId);
	var dateValue = $("#" + inpFieldName).val();
	
	if (dateValue!=null){
		var arrDate = dateValue.split("#");
		 $("#" + inpFieldName  + "nnDay").val(arrDate[0]);
		 $("#" + inpFieldName  + "nnMonth").val(arrDate[1]);
		 $("#" + inpFieldName  + "nnYear").val(arrDate[2]);	
	}

}

function resetKids(pId){

	var kids = $("#trKids" + pId).val();
	var arrKids = kids.split("|");
	var newKids = "";

	for(var i=0; i<arrKids.length; i++) {
		var value  = arrKids[i];
		if (document.getElementById('budgetTr' + value)==null){
		}
		else {
			if (	$("#trLineParent_" + value).val() ==  pId) {			
				newKids += value + "|";						
			}
		}
	}
	$("#trKids" + pId).val(newKids);
}

function getHtmlEntity(str){
	str = myReplace(str,"&amp;", "&");
	str = myReplace(str,"&lt;", "<");
	str = myReplace(str,"&gt;", ">");
	str = myReplace(str,"&nbsp;", " ");
	str = myReplace(str,"<space>", " ");
	
	

	return str;

}

function showSort() {
	if ( $("#showLineSort").val() == "1" ) 
		return true;
	else
		return true;
	
}

//
// handle cut & paste
//
var globalCutRowId = "a";
function doCut(cutType, rowId){

	if ( globalCutRowId == rowId) {
		dismissCut();
	}	
	else if (cutType==TR_TYPE_LINE) {
		 if ( IsNumeric(globalCutRowId)) {
			// change line position:

			myMoveRow(globalCutRowId , rowId);

			// change line position:
			var oldParent = $("#trLineParent_" + globalCutRowId).val();
			var newParent = $("#trLineParent_" + rowId).val();
			
			if (oldParent!=newParent){
				 $("#trLineParent_" + globalCutRowId).val(newParent);
				var currentKids = $('#trKids' + newParent).val();	
				currentKids += "|" + globalCutRowId; 
				$('#trKids' + newParent).val(currentKids);
				
				resetKids(oldParent);
			}
			dismissCut();
			budgetIsChanged();
			calcLine(1, rowId);
			calcP(oldParent, true);
			
			
			
		}
		else {
			
			$(".imgMoveLine").attr("src" , imgMoveHereSrc);
			$(".imgMoveLine").attr("title" , "Move to here");
			$("#imgMove_" + rowId).attr("src" , imgMoveMeSrc);
			$("#imgMove_" + rowId).attr("title" , "Move me");
			$(".imgMoveP").css("visibility","hidden");
			globalCutRowId = rowId;	
			moveIsOnn = true;
		}
	}
	else if (cutType==TR_TYPE_PARAGRAPH) {
		
		if ( IsNumeric(globalCutRowId)) {
			
			//part 1: create the new P
			myMoveRow(globalCutRowId , rowId);			
			
			//part 2: create the lines under P
			var kids = $("#trKids" + globalCutRowId).val();
			var arrKids = kids.split("|");			

			for(var i=0; i<arrKids.length; i++) {
				var value = arrKids[i];
				if (document.getElementById('budgetTr' + value)==null){
				}
				else {
					myMoveRow(value , rowId);
				}
			}
			
			//part 3: create the "add new line" under P			
			var addNewLine = $('#trAddNewLineFor' + globalCutRowId).val();
			myMoveRow(addNewLine , rowId);
			
			dismissCut();
			budgetIsChanged();
				
			
		}
		else {

			$(".imgMoveP").attr("src" , imgMoveHereSrc);
			$(".imgMoveP").attr("title" , "Move to here");
			$("#imgMove_" + rowId).attr("src" , imgMoveMeSrc);
			$("#imgMove_" + rowId).attr("title" , "Move me");
			$(".imgMoveLine").css("visibility","hidden");
			globalCutRowId = rowId;	
			moveIsOnn = true;
		}
	
	
	}
	
	
}

function dismissCut(){
	if (moveIsOnn){
		$(".imgMoveLine").attr("src" , imgMoveSrc);
		$(".imgMoveLine").css("visibility","visible");
		$(".imgMoveLine").attr("title" , "Move this line");
		$(".imgMoveP").attr("src" , imgMoveSrc);
		$(".imgMoveP").css("visibility","visible");
		$(".imgMoveP").attr("title" , "Move this line");
		moveIsOnn = false;

		globalCutRowId = "a";
	}

}

function myMoveRow(rowId, newRowId){
	var row = document.getElementById('budgetTr' + rowId);
	var newRow = document.getElementById('budgetTr' + newRowId);
	var parent = document.getElementById("tblBudgetBody");

	row.parentNode.removeChild(row);  
	parent.insertBefore(row, newRow);
}

$(document).keyup(function(e) {   
	//if (e.keyCode == KEYCODE_ENTER) { $('.save').click(); }   
	if (e.keyCode == KEYCODE_ESC) {
		if (moveIsOnn){
			dismissCut(); 
		}
	}  
}); 

//
// handle editors
//

function showSheetEditors(sheetId){
var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	html += "<span class='smallWindowTitle'>Spreadsheet Editors</span><br>";
	html += "<div style='font-size: 12px; padding: 6px 0px 20px 4px; color: black;'>Allow other users to edit this spreadsheet </div>";
	//html += "<span style='font-size: 12px; padding-left: 4px; color: #808080;'>(the user need to sign up to calculito with that email) </span><br><br>";
	
	
	html += "<input type='hidden' id='editorSheetId' value='" + sheetId + "'  >";
	html += "<table id='tblEditors' bgcolor='gainsboro' style='padding:5px; font-size:14px; line-height: 18px; border: 1px solid #708090;' >";

	html += "<tr>";
	html += "<td class='tdEditUser' >User Email</td>";
	html += "<td class='tdEditUser' >Permission</td>";
	html += "<td class='tdEditUser' ></td>";
	html += "</tr>";	
	
	html += "<tr>";
	html += "<td class='tdEditUser' ><input id='newEditorEmail' style='width:150px; height: 15px;' ></td>";
	html += "<td class='tdEditUser' >";
	
	html += "<select id='newPermission' >";
	html += "<option value='1' >Edit</option>";
	html += "<option value='2' >Read Only</option>";
	html += "</select>";			
	
	html += "</td>";
	html += "<td class='tdEditUser' ></td>";
	html += "</tr>";	

	html += "<tr><td>";
	html += "<div id='spnMsgEditor' style='color: red; padding: 3px; display: none;'></div>";
	html += "&nbsp;<a class='aDropLine' href='#' id='submitUser' >Save New Editor</a><br><br>";	
	html += "</td></tr>";
	html += "<tr>";
	html += "<td nowrap></td></tr>";		
	html += "</table>";	
	
	
	
	html += "<br><span id='editorMsg' style='color:red; padding: 3px;'></span><br>";
	html += " &nbsp;&nbsp; ";	
	html += "<input type='button' class='inpButton' value=' Close This Window ' id='hideWindow' />";	
	html += "<br><br><br><br><br>";		
	html += "<div class='divHelpText' >";		
	html += "Once the user you've added is signed up to Calculito ";
	html += "with the email you entered, he can start using ";
	html += "the spreadsheet. ";
	html += "</div>";
	html += "<br><br>";		
	
	document.getElementById("registerInner").innerHTML = html;
	
	createSheetEditorLines(sheetId);
	
	$('.inpNewBudget').css('width', '200px;');
	$('#submitBudget').css('color', 'green');
	$('#submitBudget').css('font-weight', 'bold');

	$("#submitUser").click(function(event) {   
		addNewEditor(); 		
		event.preventDefault();
	});   
	
	$("#hideWindow").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$('#registerContent').animate({		
		width:  '500px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 
	$("#windowMsg").hide();
	


}

function createSheetEditorLines(sheetId){
	var time1 = get_time();	
	$.get("getSheetEditor.php?sheetId=" + sheetId + "&t=" + time1, function(data) {
		
		if (data.length > 1){
			var arrAllEditors = data.split(";");

			for(var i2=0; i2 <arrAllEditors.length; i2++) {
				
				var editorValues = arrAllEditors[i2];
				var arrEditor = editorValues.split("#");
				
				var originalId = arrEditor[0];
				var userEmail = arrEditor[1];
				var permissionId = arrEditor[2];
				
				createNewEdiotrLine(originalId,userEmail,permissionId);
				
			}
		}
	});
}


function addNewEditor(){
	var newEmail = $("#newEditorEmail").val();
	var newPermission = $("#newPermission").val();
	$("#spnMsgEditor").html(""); 
	$("#spnMsgEditor").hide();
	
	if (isValidEmail(newEmail)){
		var time1 = get_time();	
		$.get("checkEmail.php?emailAddress=" + newEmail + "&t=" + time1, function(data) {
		
			validEmail=data;
			var addLine = false;
			if (validEmail=="3"){
				addLine = true;
			}
			if (validEmail=="0"){
				$("#spnMsgEditor").html( "Not a valid email address");
				$("#spnMsgEditor").show();
			}
			else if (validEmail=="1"){
				addLine = true;
			}
			
			if (addLine ){
					
				createNewEdiotrLine(-1,newEmail,newPermission);
			}
		});
	}
	else {
		$("#spnMsgEditor").html("Not a valid email address");	
		$("#spnMsgEditor").show();
	}
}

function createNewEdiotrLine(originalId,newEmail,newPermission){
	var parent = document.getElementById("tblEditors");		
	var rowCount = parent.getElementsByTagName("tr").length;

	var myRow = $("#tblEditors" )[0].insertRow(rowCount);
	myRow.id = "tr" + rowCount;
	$("#"  + myRow.id).css("background", "whitesmoke");	
	
	var html = "";
	
	html += "<td class='tdExistsEditor' id='td" +  rowCount+ "'> ";
	html +=  newEmail;
	html += " </td>";
	html += "<td class='tdExistsEditor' >";
	if (newPermission=="1"){
		html += " Edit "; 
	}
	else {
		html += " Read Only "; 
	}			
	html += "</td>";
	html += "<td class='tdExistsEditor' >";
	html  += "<a class='aDropLine' href='javascript:dropEditorLine(\"td" + rowCount + "\"," + originalId + ");' >Remove Editor</a>";	
	
	$("#" + myRow.id ).html(html);		
	
	var dataString = "";
	dataString += "sheetId=" + $("#editorSheetId").val();
	dataString += "&newEditorEmail=" + newEmail;
	dataString += "&newPermissionId=" + newPermission;
	dataString += "&actionId=1";
	
	if (originalId == -1 ){
	
		$.ajax({   
			type: "POST",   
			url: "sheetEditor.php",   
			context: document.body,
			data: dataString,   
			success: function(){  						
			}
		});
	}

}

function dropEditorLine(lineId, originalId){

	var t = document.getElementById(lineId);	
	var trId  = t.parentNode.id;
	var rowIndex = document.getElementById(trId).rowIndex;
	document.getElementById("tblEditors").deleteRow(rowIndex);	
	
	if (originalId != -1){
		var dataString = "";
		dataString += "sheetEdiotrId=" + originalId;
		dataString += "&actionId=2";
		
	
		$.ajax({   
			type: "POST",   
			url: "sheetEditor.php",   
			context: document.body,
			data: dataString,   
			success: function(){  						
			}
		});
		
	
	}

}

function getCurrentDate(){
	var d = new Date();
	var result = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
	//alert(result);
	return result;
}

function getTrackerDate(dateValue){
	if (dateValue.length < 8){
		return getCurrentDate();
	}
	else {
		return dateValue;
	}


}

function isLegalDate(dateValue){
   var isLegal = false;
   var arrDateValues = dateValue.split("/");
   if (arrDateValues.length = 3){
		if ( IsNumeric(arrDateValues[0]) && IsNumeric(arrDateValues[1]) && IsNumeric(arrDateValues[2]) ){
			isLegal = true;
		}   
   }
   return isLegal;
}

function showTrackerDatePicker(fieldName){

	if (!isDate( $("#" + fieldName).val() ) ){
		var today = new Date();
		var saveDate = (today.getMonth() + 1) + "/" +  today.getDate() + "/" + today.getFullYear();				
		$("#" + fieldName).val(saveDate);
	}

	$('#' + fieldName).click();
}

function setTrackerDates(trackerDate){
	var myDate;
	if (isLegalDate(trackerDate)) {
		myDate = trackerDate;
	}
	else {
		myDate = getCurrentDate;
	}
	
	var arrDateValues = myDate.split("/");
	var myDay = arrDateValues[1];
	var myMonth = arrDateValues[0];
	var myYear = arrDateValues[2];


	var trackerDate = new Date();
	var finalDate = new Date();
	
	myMonth = (myMonth - 1);
	
	trackerDate.setFullYear(myYear,myMonth, myDay);
	finalDate.setFullYear(myYear,myMonth, myDay);
	
	var weekDay = trackerDate.getDay();
	if (weekDay==0){
		finalDate.setDate(finalDate.getDate() - 6); 
	}
	else {
		finalDate.setDate(finalDate.getDate() - weekDay + 1);
	}
	
	var newHeader = "";
	var tempDate = new Date();
	tempDate = finalDate;
	
	/*
	$(".td2_hdr").css;
	$(".td3_hdr").hide();
	$(".td2_hdr").show(0);
	$(".td3_hdr").show(0);
	*/
	//showSavingWindow("Updating Dates", 1400);
	
	arrTrackerDates = [];
	var saveDate;
	
	$(".inpValue").val("0");
	$(".inpValue").css("color","#707070");
	$(".divValueP").val("0");
	$(".editLongText").hide();
	$(".editTrackerValues").hide(); 
	$(".inpValue").css("width","57px");
	
	
	for(var i=0; i < 7; i++) {		

		var currentMonth = tempDate.getMonth() ;
		var dayOfWeekName = getDayName( i + 1 );
		currentMonth++;

		newHeader = "";
		//newHeader += $("#tdHdr_" + i).html().substr(0 , 4);
		
		newHeader += "<span class='hdrDateDay' >" + getMonthName(currentMonth) + "&nbsp;" + tempDate.getDate() + "</span>";
		newHeader += " <br>";
		newHeader += dayOfWeekName;
		
		$("#tdHdr_" + i).html(newHeader);
		if (tempDate==Date()){
			//$("#tdHdr_" + i).css("background","#A995C2");
		}
		
		saveDate = currentMonth + "_" +  tempDate.getDate() + "_" + tempDate.getFullYear();
		arrTrackerDates[i] = saveDate;
	
		tempDate.setDate( tempDate.getDate() + 1);	
		
		getTrackerValues(saveDate, i + 1, "");
	}
	$(".hdrDateDay").css("color","red");
	var t=setTimeout('$(".hdrDateDay").css("color","#AFC297");',1400);
	

}

function getDayName(dayId){
	if (dayId==1)
		return "MON";
	else if (dayId == 2)
		return "TUE";
	else if (dayId == 3)
		return "WED";
	else if (dayId == 4)
		return "THU";
	else if (dayId == 5)
		return "FRI";
	else if (dayId == 6)
		return "SAT";
	else if (dayId == 7)
		return "SUN";

}

function getMonthName(monthId){
	if (monthId=="1")
		return "Jan";
	else if (monthId=="2")
		return "Feb";
	else if (monthId=="3")
		return "Mar";
	else if (monthId=="4")
		return "Apr";
	else if (monthId=="5")
		return "May";
	else if (monthId=="6")
		return "Jun";
	else if (monthId=="7")
		return "Jul";
	else if (monthId=="8")
		return "Aug";
	else if (monthId=="9")
		return "Sep";
	else if (monthId=="10")
		return "Oct";
	else if (monthId=="11")
		return "Nov";
	else if (monthId=="12")
		return "Dec";

}

function saveTrackerValue(rowId, fieldId, trackerValue, trackerDateValue, trackerNote, trackerId){

	var igonreOld = "";
	if (trackerDateValue.length > 0){
		var arr_dates = trackerDateValue.split("/");
		var tracker_month = arr_dates[0];
		var tracker_day = arr_dates[1];
		var tracker_year = arr_dates[2];
		
		if (tracker_day.substr(0,1) == "0"){
			tracker_day = tracker_day.substr(1,1);
		}
		//var trackerDate = myReplace(trackerDateValue,"/","_");
		var trackerDate = tracker_month + "_" + tracker_day + "_" + tracker_year;
		igonreOld = "true";
		
		var rowKey = rowId;
	}
	else {
		var fieldName = getInpFieldName(fieldId, rowId);
		var trackerDate = arrTrackerDates[fieldId - 1];
		var rowKey = $("#rowKey_" + rowId).val();
	}
	
	var finalTrackerId = trackerId; 
	if (finalTrackerId == ""){
		finalTrackerId = get_time();
	}
		
	
	var dataString = "";
	dataString += "rowId=" + rowKey;
	dataString += "&trackerDate=" + trackerDate;
	dataString += "&trackerValue=" + trackerValue;		
	dataString += "&trackerId=" + finalTrackerId;		
	dataString += "&igonreOld=" + igonreOld;
	dataString += "&trackerNote=" + trackerNote;
	dataString += "&sheetTempId=" + $("#sheetTempId").val();	
	//dataString += "&trackerNote=" + $("#" + fieldName + "xxxnote").val();
	
	$.ajax({   
		type: "POST",   
		url: "saveTracker.php",   
		context: document.body,
		data: dataString,   
		success: function(){  								
				//alert("done");
		}
	});
	
}


function saveMultiTrackerValue(rowId, fieldId){

	
	var i = 0;
	var lineId = "";
	var tempId = "";
	var trackerValue = "";
	var trackerNote = "";
	var trackerId = "";
	
	var fieldName = getInpFieldName(fieldId, rowId);
	$('#' + fieldName).val("0");

	
	$("#tblTrackerSmall tr").each(function(t){
		if (i > 0){
			//get Line id
			tempId = this.id;

			lineId = tempId.substr(2, tempId.length - 2);
			if (trackerValue.length > 0){
				trackerValue += ITEM_SEPERATE_1;
				trackerNote += ITEM_SEPERATE_1;				
				trackerId += ITEM_SEPERATE_1;				
			}
			trackerValue += $("#inpTrkValue" + lineId).val();
			trackerNote += $("#inpTrkNote" + lineId).val();
			trackerId += lineId;			
		
		}	
		i++;
	});		
	
	if (trackerValue.length == 0){
		trackerValue = "0";
	}
	
	var fieldName = getInpFieldName(fieldId, rowId);
	var trackerDate = arrTrackerDates[fieldId - 1];
	var rowKey = $("#rowKey_" + rowId).val();
	
	
	var dataString = "";
	dataString += "rowId=" + rowKey;
	dataString += "&trackerDate=" + trackerDate;
	dataString += "&trackerValue=" + trackerValue;		
	dataString += "&trackerId=" + trackerId;		
	dataString += "&sheetTempId=" + $("#sheetTempId").val();	
	dataString += "&trackerNote=" + trackerNote;
	dataString += "&multiTracker=true";		
	
	
	$.ajax({   
		type: "POST",   
		url: "saveTracker.php",   
		context: document.body,
		data: dataString,   
		success: function(){  								
				
			var trackerDate = $('#inpTrkEditDate').val();
			var fieldId = $('#inpTrkEditFieldId').val();
			var rowId = $('#inpTrkEditRowId').val();
			
			getTrackerValues(trackerDate,fieldId,rowId);
			hidwWindowFast(); 
			
		}
	});
	
}


function getTrackerValues(trackerDate,fieldId,lineId){
	var dataString = "";
	dataString += "&trackerDate=" + trackerDate;
	dataString += "&sheetTempId=" + $("#sheetTempId").val();	

	var time1 = get_time();			
	
	$.get("getTrackerValues.php?trackerDate=" + trackerDate + "&sheetTempId=" + $("#sheetTempId").val() + "&lineId=" + lineId + "&t=" + time1, function(data) {
		//alert(data);
		if (data!=undefined){
			
			arrTrackerValue = data.split(ITEM_SEPERATE_1);
			for(var i1=0; i1 <arrTrackerValue.length; i1++) {
				var dayValues = arrTrackerValue[i1];
				arrValues = dayValues.split(ITEM_SEPERATE_2);
				
				var rowId = arrValues[0];
				var trackerValue = arrValues[1];
				var trackerNote = arrValues[2];
				
				var sheetRowId = $("#rowIdByKey_" + rowId).val();
				
				if (document.getElementById('rowIdByKey_' + rowId)!=null){ 
				
					if (trackerValue.indexOf(".") > 0){
						var floatValue = parseFloat(trackerValue);
						trackerValue = floatValue.toFixed(2);
					}
					
					var fieldName = getInpFieldName(fieldId, sheetRowId);					
					var fieldCurrentValue = parseFloat( $("#" + fieldName).val() );
					
					if (fieldCurrentValue > 0){
						trackerValue = parseFloat(trackerValue) + fieldCurrentValue;
					}
					
					$("#" + fieldName).val(trackerValue);		
					$("#" + fieldName).css("color","black");
					$("#" + fieldName + "xxxnote").val(trackerNote);		
					
					
					
					calcLine(1, sheetRowId);
					showTrackerNote(fieldId, sheetRowId);
				}
				
			}
			
		}
	});
	

}

function showTrackerNote(fieldId, newRowId){
	
	var inpFieldName = getInpFieldName(fieldId, newRowId);
	var trackerValue =  $("#" + inpFieldName).val();
	
	if (trackerValue  == "0" ){
		$("#" + inpFieldName + "xxxpen").hide();
		$("#" + inpFieldName).css("width", "57px");
		$("#" + inpFieldName).css("color","#707070");
	}
	else {
		$("#" + inpFieldName + "xxxpen").show();
		$("#" + inpFieldName).css("width", "49px");
		
	}
	
	
	
}

function isTracker() {
	if ($("#isTracker").val() == "true")
		return true;
	else
		return false;


}

function showSelectZone(){
	var time1 = get_time();	
	globalHtml = "";
	$.get("getZoneList.php?t=" + time1, function(data) {
		var html = "";

		document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

		html += "<span class='smallWindowTitle'>Select Category</span><br><br>";
		html += "<table cellspacing='0' cellpadding='0' border='0'  style='background: #EAEFBD; width: 300px; padding: 5px 5px 0px 5px; border: 1px solid gainsboro;' >";

		var arrZones = data.split(";");

		for(var i=0; i <arrZones.length; i++) {
			var zoneValue = arrZones[i];
			var arrZoneValue = zoneValue.split("#");
			
			html += "<tr><td nowrap valign='middle' style='border-bottom: 1px solid gainsboro; padding-left: 12px; line-height: 40px;'>";	
			html += "<a href='?zoneId="  + arrZoneValue[0] + "'class='aSelectZoneSmall' >";
			html += "<img src='" + arrZoneValue[2]  + "' class='imgSpreadsheetIcon' border='1' width='30' height='30' >" ;
			html += "</a>";
			html += "</td>";
			html += "<td style='border-bottom: 1px solid gainsboro; padding-left: 12px; line-height: 40px;'>";
			html += "<a href='?zoneId="  + arrZoneValue[0] + "'class='aSelectZoneSmall' >";
			html += arrZoneValue[1] ;
			html += "</td></tr>";	
		}
	
		html += "</table><br>";	
		html += "<input type='button' class='inpButton' value=' Close ' id='hideWindow' />";	
		html += "<br><br><br>";		
		
		document.getElementById("registerInner").innerHTML = html;
		
		$('.inpNewBudget').css('width', '200px;');

		$("#hideWindow").click(function(event) {   
			hidwWindow();
			event.preventDefault();
		});   
		
		$('#registerContent').animate({		
			width:  '530px'
		});

		$("#registerWindow").show();
		$("#registerContent").fadeIn("fast"); 
	});



}

function showSaveBeforeTrack(strAction){
	var html = "";

	document.getElementById("registerContent").style.left = document.getElementById("tdLeftMargin").offsetWidth;

	if (strAction=='print'){
		html += "<span class='smallWindowTitle'>Printable Spreadsheet</span><br><br>";
		html += "<div style='line-height: 28px; font-size: 14px;'>";
		html += "Before you can print you have to ";
		html += "<a class='aBefore' href='javascript:saveCurrentBudget(true);' >Create a free account</a>.<br>";
		html += "Thanks.<br>";
	}
	else if (strAction=='pie'){
		html += "<span class='smallWindowTitle'>Pie Chart</span><br><br>";
		html += "<div style='line-height: 28px; font-size: 14px;'>";
		html += "Before you can view the reports and graphs "; 
		html += "you need to save this spreadsheet.<br>";
		html += "<a class='aBefore' href='javascript:saveCurrentBudget(true);' >Create a free account</a>.<br>";
		html += "Thanks.<br>";
	}
	else {
		html += "<span class='smallWindowTitle'>The Daily Tracker</span><br><br>";
		html += "<div style='line-height: 28px; font-size: 14px;'>";
		html += "The <b>Daily Tracker</b> is a useful money management tool to track your<br>";
		html += "actual costs and see if you're sticking to the budget. <br>";
		html += "";
		html += "To start using the <b>Daily Tracker</b> create a free account and   ";
		html += "<a class='aBefore' href='javascript:saveCurrentBudget(true);' >Save this budget</a> .<br><br>";
	}
	html += "</div><br>";
	
	html += "<input type='button' class='inpButton' value=' Close ' id='hideWindow' />";	
	html += "<br><br><br>";		
	
	$('.aBefore').css('font-size', '14px;');
	$('.aBefore').css('color', 'green;');

	document.getElementById("registerInner").innerHTML = html;
	
	$('.inpNewBudget').css('width', '200px;');
	$("#hideWindow").click(function(event) {   
		hidwWindow();
		event.preventDefault();
	});   
	
	$('#registerContent').animate({		
		width:  '530px'
	});

	$("#registerWindow").show();
	$("#registerContent").fadeIn("fast"); 


}

var arrTrackerComboParent = [];
var arrTrackerCombo = [];
function createTrackerComboArr(parentRowKey, rowKey, rowType, rowTitle){
	
	if (rowType==TR_TYPE_PARAGRAPH){
		
		var arrValue = new Object;
		arrValue.rowTitle = rowTitle;
		arrValue.rowKey = rowKey;
		arrTrackerComboParent.push(arrValue);
	}
	else if (rowType==TR_TYPE_LINE) {
		var arrValue = new Object;
		arrValue.rowTitle = rowTitle;
		arrValue.rowKey = rowKey;		
		arrValue.parentRowKey = parentRowKey;		
		arrTrackerCombo.push(arrValue);
	}
}

function createTrackerQuickAdd(){

	var html = "";
	//html += "<div style='font-size: 14px; font-weight: bold; padding: 13px;' >Create new Actual Cost</div>";
	html += "<table id='tblTrackerSmallQuick'  name='tblTrackerSmallQuick' cellspacing='1' ><tbody>";
	//headers
	html += "<tr>";
	html += "<td class='tdSmallHdr'>Category</td>";
	html += "<td class='tdSmallHdr'>Sub Category</td>";
	html += "<td class='tdSmallHdr'>Date</td>";
	html += "<td class='tdSmallHdr'>Amount</td>";
	html += "<td class='tdSmallHdr'>Note</td>";
	html += "</tr>";
	//new line
	html += "<tr>";
	
	html += "<td class='tdSmallNew'>";
	html += "<select id='selectCatParent' >";
	html += "<option value='--' style='color:gainsboro;font-size:11px;' >--no value--</option>";	
	for(var i=0; i < arrTrackerComboParent.length; i++) {		
		arrValue = arrTrackerComboParent[i];
		
		html += "<option value='" + arrValue.rowKey + "' >" + arrValue.rowTitle + "</option>";	
	
	}
	
	html += "</select></td>";
	html += "<td class='tdSmallNew'>";
	html += "<select id='selectCat' >";
	html += "<option value='--' style='color:gainsboro;font-size:11px;' >--no value--</option>";	
	html += "</select></td>";   
	
	html += "<td class='tdSmallNew'>";
	html += '<input id="newTrackerDate" value="" style="width: 120px;" readonly/>';
	html += "</td>";

	html += "<td class='tdSmallNew'>";  
	html += '<input id="newTrackerAmount"  value="0" style="text-align: right; width: 65px;" />';
	html += "</td>";

	html += "<td class='tdSmallNew'>";
	html += '<input id="newTrackerNotes" value="" style="width: 120px;" />';
	html += "</td>";

	html += "</tr>";
	html += "<tr>";
	html += "<td valign='top' colspan='5' style='padding:10px 0px 10px 10px; background: whitesmoke; line-height: 50px;' >";
	
	html += "<table><tr><td>";
	html += "<a href='javascript:createNewTrackerLineQuick();' class='' ><img  src='images/SAVE.png' border='0' ></a>";
	html += "</td>";
	html += "<td style='padding-left: 40px;'>";
	html += "<span id='newTrackerMsg' style='color:red;font-weight:bold;' ></span>";
	html += "</td></tr></table>";
	
	html += "</td>";
	html += "</tr>"; 
	
	html += "</tbody>";
	html += "</table>";
	$(".trackerContainer").html(html);
	
	$("#selectCatParent").change(function() {   
		selectCatCombo( $(this).val() );
	});   
	
	$('#newTrackerDate').val(getCurrentDate() );
	implementDate('newTrackerDate');
	$('#newTrackerDate').css("width","120px");
	

	$("#newTrackerAmount").change(function() {

		if (!IsNumeric( $(this).val() )){
			$(this).val("0");			
		}
	});

}

function selectCatCombo(value){
	var combo = document.getElementById("selectCat");
	combo.options.length=0;	
	combo.options[0]=new Option("--no value--", "--", false, false);
	
	var option_counter = 1;
	for(var i=0; i < arrTrackerCombo.length; i++) {			
		
		arrValue = arrTrackerCombo[i];
		if (arrValue.parentRowKey == value){
		
			combo.options[option_counter]=new Option(arrValue.rowTitle, arrValue.rowKey, false, false);
			option_counter++;
		}
	
	}
	
}

function createNewTrackerLineQuick(){
	//alert("new line");
	//newTrackerDate  selectCat newTrackerAmount newTrackerNotes newTrackerMsg
	var newCategoty = $("#selectCat").val();
	var newDate = $("#newTrackerDate").val();
	var newAmount = $("#newTrackerAmount").val();
	var newNote = $("#newTrackerNotes").val();
	var isLegal = true; 
	$("#newTrackerMsg").html("");
	
	if (newCategoty=="--"){
		$("#newTrackerMsg").html("Please select a category");
	}
	else if (newAmount=="0"){
		$("#newTrackerMsg").html("Amount can't be zero");
	}
	else {
	
		
		var w = document.getElementById("selectCat").selectedIndex;
		var cat_text = document.getElementById("selectCat").options[w].text;
		
		w = document.getElementById("selectCatParent").selectedIndex;
		var cat_parent_text = document.getElementById("selectCatParent").options[w].text;		

		var lineId = get_time();			
		
		var parent = document.getElementById("tblTrackerSmallQuick");		
		var rowCount = parent.getElementsByTagName("tr").length;
		
		var myRow = $("#tblTrackerSmallQuick")[0].insertRow(-1);
		
		myRow.id = "tr" + lineId;	

		var html = "";
		
		html += "<td class='tdTarkcerData'>" + cat_parent_text + "</td>";		
		html += "<td class='tdTarkcerData'>" + cat_text + "</td>";		
		html += "<td class='tdTarkcerData'>" + newDate + " </td>";		
		html += "<td class='tdTarkcerData' align='right' >" + newAmount + "</td>";		
		html += "<td class='tdTarkcerData'>" + newNote + "</td>";		
		html += "<td><a class='aDropTracker' href='javascript:dropTrackerLineQuick(\"" + lineId + "\",\"" + newCategoty + "\",\"" + newDate + "\");' >Drop</a></td>";		
		$("#" + myRow.id ).html(html);			
		
		$("#newTrackerAmount").val("0");
		$("#newTrackerNotes").val("");
		
		// saveTrackerValue(rowId, fieldId, trackerValue, trackerDateValue, trackerNote){
		 saveTrackerValue(newCategoty, "", newAmount, newDate, newNote, lineId);

	}	
}

function dropTrackerLineQuick(lineId,CategoryId,trackerDate){
	
	var rowIndex = null;
    var rows = document.getElementById('tblTrackerSmallQuick').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
		//alert(rows[i].id);
		if (rows[i].id == ("tr" + lineId)){
			
            rowIndex = rows[i].rowIndex;
        }
    }
	if (rowIndex != null){
		document.getElementById("tblTrackerSmallQuick").deleteRow(rowIndex);	
	}
		
	saveTrackerValue(CategoryId, "", "0", trackerDate, "", lineId);
		
}


function showTrackerQuickAdd(mode){
	if (mode=="show"){
		$(".budgetContainer").hide();
		$(".trackerDateSelector").hide();
		$("#aSaveBudget").hide();		
		$(".trackerContainer").fadeIn(1000);
		$(".aTrackerCalendarMode").css("color","green");
		$(".aTrackerQuickMode").css("color","black");
		$(".aTrackerQuickMode").css("background","#E8E1E1");
		$(".aTrackerCalendarMode").css("background","gainsboro");
		
	}
	else {
		$(".trackerContainer").hide();
		$(".budgetContainer").fadeIn(1000);
		$(".trackerDateSelector").fadeIn(1000);
		$("#aSaveBudget").fadeIn(1000);		
		$(".aTrackerCalendarMode").css("color","black");
		$(".aTrackerQuickMode").css("color","green");
		$(".aTrackerQuickMode").css("background","gainsboro");
		$(".aTrackerCalendarMode").css("background","#E8E1E1");
		setTrackerDates($('#trackerDate').val() );


	}

}

function isDate(dateStr) {

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null) {
//alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
return false;
}

month = matchArray[1]; // p@rse date into variables
day = matchArray[3];
year = matchArray[5];

if (month < 1 || month > 12) { // check month range

	return false;
}

if (day < 1 || day > 31) {
	
return false;
}

if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	
return false;
}

if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap)) {
//alert("February " + year + " doesn`t have " + day + " days!");
return false;
}
}
return true; // date is valid
}
