function cmsImagePopup(url, width, height)
{
	

}

function changeDownspenderType(val)
{
	$('tbody.type').hide();
	$('#' + val).show();
}

function getMoreInfo()
{
	
}

//Autocomplete

 function findValue(li) {
if( li == null ) return alert("No match!");

// if coming from an AJAX call, let's use the Id as the value
if( !!li.extra ) var sValue = li.extra[0];

// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;

}

function selectItem(li) {

findValue(li);
}

function formatItem(row) {
return row[0] + " (id: " + row[1] + ")";
}

function lookupAjax(){
var oSuggest = $("#paymentsBuilderName1")[0].autocompleter;
//alert(print_r(oSuggest));
//oSuggest.findValue();
return false;
}

///

function print_r(theObj){
  var returnValue = "";
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    returnValue += "<ul>";
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
		returnValue += "<li>["+p+"] => "+typeof(theObj)+"</li>";
        returnValue += "<ul>";
        print_r(theObj[p]);
        returnValue += "</ul>";
      } else {
		returnValue += "<li>["+p+"] => "+theObj[p]+"</li>";
      }
    }
    returnValue += "</ul>";
  }
  else
  {
  	returnValue = "Not array or object";
  }
  return returnValue;
}


function fillNumber(sender)
{
	var thisRowID = getNum(sender.id);
	$('#paymentsNetAmount' + thisRowID).val(formatAsMoney(roundValue(sender.value  / (1 + gstRate), 2)));
	calculateTotals();
}

function calculateTotals()
{
	var totalNet = 0;
	var teamPoints = 0;
	var total = 0;
	var totalNetPoints = 0;
	
	$('.dateRecd').each(
		function()
		{
			
			if(this.value == "")
			{
				this.value = month_ending;
			}
		}
	);
	
	$('.grossAmount').each(
		function()
		{
			var rowCount = getNum(this.id);
			var cost = roundValue(parseFloat(getNum(this.value)), 2);
			var rate = parseFloat($('#payments_point_percent' + rowCount).val());
			total += cost;
			totalNet += roundValue(cost / (1 + gstRate) , 2);
			teamPoints += roundValue(cost / (1 + gstRate) * rate/100, 2);
			totalNetPoints += roundValue(total / (1 + gstRate) * rate / 100, 2);
			//this.val(formatAsMoney(this.value))
		}
	);
	//perc = $('#PointPercent').val() / 100;
	
	$('#totalNet').html(formatAsMoney(totalNet));
	//percVal = totalNet * perc;
	percVal = totalNetPoints;
	$('#PointPercTotal').html(formatAsMoney(teamPoints));
	sub = teamPoints + parseFloat($('#base_add_fee').html());
	$("#subTotal").html(formatAsMoney(sub));
	gstOfSub = sub * gstRate;
	$("#gst").html(formatAsMoney(gstOfSub));
	$("#grandTotal").html(formatAsMoney(sub + gstOfSub));
	//alert(totalNet);
}

function roundValue(value, decimal)
{
	if(typeof(decimal) == 'undefined')
		decimal = 0;
	var multipler = 1;
	for(var i = 0; i < decimal; i++)
	{
		multipler = multipler * 10;
	}
	return Math.round(value * multipler)/multipler;
}

function formatAsMoney(ObjVal)
{
 //Obj.value = formatAsMny(Obj.value)
 mnt = ObjVal;
 mnt -= 0;
 mnt = (Math.round(mnt*100))/100;
 ObjVal = (mnt == Math.floor(mnt)) ? mnt + '.00' : ( (mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);
 if (isNaN(ObjVal)) {ObjVal ="0.00";}
 return ObjVal;
}


/**
*	add another table row of 
*   
*/

function add10RowsToTable()
{
	for($i = 0; $i < 10; $i = $i + 1)
	{
		addRowToTable();
	}
	calculateTotals();
}

function addRowToTable()
{
	var html = '		    	<tr id="row0" class="payment"> ';
    html +=	'	<td class="nowrap"> ';
    html +=	'			<a href="#payments" class="deleteLink" onclick="return deleteTableRow(\'row0\', \'Are you sure to remove this row?\');">Delete</a> ';
    html +=	'		</td> ';
    html +=	'		<td nowrap> ';

    html +=	'			<input type="text" id="paymentsDateRecd0" name="payments[0][dateRec]" value="" class="dateRecd input" style="width:71px;" > ';
    html +=	'		</td> ';
    html +=	'		<td> ';
    html +=	'			<input type="text" id="paymentsBuilderName0" name="payments[0][builderName]" class="input" value="" > ';
    html +=	'		</td> ';
    html +=	'		<td> ';
    html +=	'			<input type="text" id="paymentsBuilderNumber0" name="payments[0][builderNumber]" value="" class="builderNumber input" style="width:111px;" > ';
    html +=	'		</td> ';
    html +=	'		<td> ';

    html +=	'			<input type="text" size="5" id="payments_point_percent0" onchange="calculateTotals();" name="payments[0][point_percent]" value="1" class="point_percent input">  %';
    html +=	'		</td> ';
    		
    html +=	'		<td nowrap> ';
    html +=	'			$ <input type="text" id="paymentsGrossAmount0" onchange="fillNumber(this)" name="payments[0][grossAmount]" value="" class="grossAmount input" style="width:81px;"> ';
    html +=	'		</td> ';
    		
   html +=	' 		<td  nowrap> ';
   html +=	' 			$ <input type="text" id="paymentsNetAmount0" name="payments[0][netAmount]" value="" readonly="true" class="netAmount input" style="width:81px;" > ';
   html +=	' 		</td> ';

   html +=	' 	</tr>	';

		
/*		$('#payments tr').each(
			function(i)
			{
				var id = parseInt(getNum(this.id));
				if(id > nextRowId)
				{
					nextRowId = id;
				}
				$(this).addClass((i%2)? 'even':'');
			}
		);	*/

		$(html.replace(/0/g, nextRowId)).appendTo('#payments');	
		$('#row' + nextRowId).each(
			function()
			{
				enableInvoice(this);
			}
		);
		
		nextRowId++;
/*		var html = '<tr id="row0">';
		html += '<td class="nowrap"><a href="#payments" class="deleteLink" onclick="deleteTableRow(\'row0\', \'Are you sure to remove this row?\');">Delete</a></td>';
		html += '<td><input type="text" id="paymentsDateRecd0" name="payments[0][dateRec]" class="dateRecd" style="width:81px;" value="" value=""></td>';
		html += '<td><input type="text" id="paymentsBuilderName0" name="payments[0][builderName]" value=""></td>';	
		html += '<td><input type="text" id="paymentsBuilderNumber0" name="payments[0][builderNumber]" class="builderNumber" style="width:111px;" value=""></td>';
		html += '<td><input type="text" size="5" id="payments_point_percent0" onchange="calculateTotals();" name="payments[0][point_percent]" value="1" class="point_percent"></td>';
		html += '<td><input type="text" id="paymentsGrossAmount0" onchange="fillNumber(this)" name="payments[0][grossAmount]" class="grossAmount" style="width:81px;" value=""></td>';
		
		html += '<td><input type="text" id="paymentsNetAmount0" name="payments[0][netAmount]" readonly="true" class="netAmount" style="width:81px;" value=""></td>'
		
		html += '</tr>';			
		nextRowId = 0;
		
		$('#payments tr').each(
			function(i)
			{
				var id = parseInt(getNum(this.id));
				if(id > nextRowId)
				{
					nextRowId = id;
				}
				$(this).addClass((i%2)? 'even':'');
			}
		);
		
		calculateTotals();
		
		nextRowId = nextRowId + 1;
		$(html.replace(/0/g, nextRowId)).appendTo('#payments');
		
		//add the mask and datepicker to the fields
		$('#paymentsDateRecd' + nextRowId).mask("99/99/9999",{placeholder:"-"});
		$('#paymentsDateRecd' + nextRowId).datepicker({dateFormat:'dd/mm/yy'});
		
		$('#paymentsBuilderName' + nextRowId).autocomplete(
			"/autocomplete.php",
			{
				delay:20,
				minChars:3,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				onItemSelect:selectItem,
				onFindValue:findValue
			}
		);*/
}

function deleteTableRow(rowId, msg)
{
	if(window.confirm(msg))
	{
		$('#' + rowId).remove();
	}
	calculateTotals();
	return false;
	
}

function getNum(str)
{
	
	if(typeof(str) != 'undefined' && str != '')
	{
		var r = str.match(/[\d\.]+/g);	
		if(typeof(r) != 'undefined' &&  r &&  typeof(r[0]) != 'undefined')
		{
			return r[0];
		}		
	}
	return 0;
};


function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

function preferdownSelected(str)
{
	for(var i in downspenders)
	{
		if(downspenders[i].oid == str.value)
		{
			$("#company").val((downspenders[i].name == null?'':downspenders[i].name));
			$("#contactPerson").val((downspenders[i].contact_person == null?'':downspenders[i].contact_person));
			$("#phone").val((downspenders[i].phone == null?'':downspenders[i].phone));
			$("#email").val((downspenders[i].email == null?'':downspenders[i].email));
			$("#bankAcc").val((downspenders[i].bank_account == null?'':downspenders[i].bank_account));
			
			

			//$("#productService").val(downspenders[i])
			//$("#amount")
		}
	}
}

function replaceSlash(source)
{
	return source.replace(new RegExp('/'),"-").replace(new RegExp('/'),"-");
}

function popWindow(theURL,width,height) {
	
newWindow = window.open(theURL,'newWindow','toolbar=no,menubar=no,resizable=no,scrollbars=no,status=no,location=no,width='+width+',height='+height);
}

function populateUsername(emailField)
{
	//oldval = $("#Username").val();
	//if(oldval == "")
	//{
		$("#Username").val(emailField.value);
	//}
}

function validate_required(field)
{
	with (field)
	{
		if (value==null||value=="")
	    {
	    	$('label[for='+$(field).attr('id')+']').attr('style', 'color:red;');
	    	return false;
	    }
		else {
			$('label[for='+$(field).attr('id')+']').css('color', '');
			return true
		
		}
	}
}

function validate_builder(thisform)
{
	isvalid = true;
	
	if(validate_required(thisform.firstname) == false)
		isvalid =  false;
		
	if(validate_required(thisform.surname) == false)
		isvalid =  false;
	
	if(validate_required(thisform.tradingname) == false)
		isvalid =  false;
		
	if(validate_required(thisform.email) == false)
		isvalid =  false;
		
	if(validate_required(thisform.address1) == false)
		isvalid =  false;
		
	if(validate_required(thisform.city) == false)
		isvalid =  false;
		
	if(validate_required(thisform.country) == false)
		isvalid =  false;
					
	if(validate_required(thisform.postalcode) == false)
		isvalid =  false;
		
	if(validate_required(thisform.businessphone) == false)
		isvalid =  false;
		
	if(validate_required(thisform.mobilenumber) == false)
		isvalid =  false;

	if(isvalid == false)
		alert('Items marked in red are required');
		
	return isvalid;
}

function validate_provider(thisform)
{
	isvalid = true;
	
	if(validate_required(thisform.contactfirstname) == false)
		isvalid =  false;

	if(validate_required(thisform.contactlastname) == false)
		isvalid =  false;
	
	if(validate_required(thisform.email) == false)
		isvalid =  false;
		
	if(validate_required(thisform.address1) == false)
		isvalid =  false;
		
	if(validate_required(thisform.city) == false)
		isvalid =  false;
		
	if(validate_required(thisform.phone) == false)
		isvalid =  false;
		
	if(validate_required(thisform.postalcode) == false)
		isvalid =  false;
		
	if(validate_required(thisform.postaladdress1) == false)
		isvalid =  false;
		
	if(validate_required(thisform.postalcity) == false)
		isvalid =  false;
		
	if(validate_required(thisform.postalpostalcode) == false)
		isvalid =  false;
		
	if(validate_required(thisform.businessnature) == false)
		isvalid =  false;
		
	if(validate_required(thisform.shareholder1) == false)
		isvalid =  false;
		
	if(validate_required(thisform.shareholder1perc) == false)
		isvalid =  false;
		
	if(validate_required(thisform.bankers) == false)
		isvalid =  false;
		
	if(validate_required(thisform.accountant) == false)
		isvalid =  false;
		
	if(validate_required(thisform.solicitor) == false)
		isvalid =  false;
		
	if(validate_required(thisform.reference1) == false)
		isvalid =  false;
		
	if(validate_required(thisform.offerings) == false)
		isvalid =  false;
		
	if(validate_required(thisform.levelofparticipation) == false)
		isvalid =  false;
		
	if(isvalid == false)
		alert('Items marked in red are required');
		
	return isvalid;
}
