var horizontal_offset="9px" //horizontal offset of hint box from anchor link
	var vertical_offset="0" //horizontal offset of hint box from anchor link. No need to change.
		var ie=document.all
		var ns6=document.getElementById&&!document.all

		function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

function iecompattest(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
	var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
			if (whichedge=="rightedge"){
				var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
						dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
						if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
							edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
			}else{
				var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
						dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
						if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
							edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
			}
	return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth){
	if ((ie||ns6) && document.getElementById("hintbox")){
		dropmenuobj=document.getElementById("hintbox")
		dropmenuobj.innerHTML=menucontents
		dropmenuobj.style.left=dropmenuobj.style.top=-500
		if (tipwidth!=""){
			dropmenuobj.widthobj=dropmenuobj.style
			dropmenuobj.widthobj.width=tipwidth
		}
		dropmenuobj.x=getposOffset(obj, "left")
		dropmenuobj.y=getposOffset(obj, "top")
		dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
		dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
		dropmenuobj.style.visibility="visible"
			obj.onmouseout=hidetip
	}
}

function showhint2(menucontents, obj, e, tipwidth){
	if ((ie||ns6) && document.getElementById("hintbox2")){
		dropmenuobj=document.getElementById("hintbox2")
		dropmenuobj.innerHTML=menucontents
		dropmenuobj.style.left=dropmenuobj.style.top=-500
		if (tipwidth!=""){
			dropmenuobj.widthobj=dropmenuobj.style
			dropmenuobj.widthobj.width=tipwidth
		}
		dropmenuobj.x=getposOffset(obj, "left")
		dropmenuobj.y=getposOffset(obj, "top")
		dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
		dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
		dropmenuobj.style.visibility="visible"
			obj.onmouseout=hidetip
	}
}
function hidetip(e){
	dropmenuobj.style.visibility="hidden"
		dropmenuobj.style.left="-500px"
}

function createhintbox(){
	var divblock=document.createElement("div")
	divblock.setAttribute("id", "hintbox")
	document.body.appendChild(divblock)
}

function createhintbox2(){
	var divblock=document.createElement("div")
	divblock.setAttribute("id", "hintbox2")
	document.body.appendChild(divblock)
}

if (window.addEventListener) {
	window.addEventListener("load", createhintbox, false)
	window.addEventListener("load", createhintbox2, false)
} else if (window.attachEvent) {
	window.attachEvent("onload", createhintbox)
	window.attachEvent("onload", createhintbox2)
} else if (document.getElementById) {
	window.onload=createhintbox
	window.onload=createhintbox2
}

function calculateTotal(elementName){
	try{
		var totalLabel = document.getElementById(elementName);
		if(totalLabel != null){
			var dynTotal = 0;
			var boxes = document.paymentForm.elements;
			for(i = 0; i < boxes.length; i++) {
				var itemToAdd = boxes[i];
				if (itemToAdd.name.indexOf('RADIO_') != -1
						&& itemToAdd.value != null
						&& itemToAdd.value != ''
							&& !isNaN(parseFloat(itemToAdd.value))) {
					if (startsWith(itemToAdd.name, 'RADIO_') || startsWith(itemToAdd.name, elementName.substring(0, elementName.indexOf('_')))) {
						if (endsWith(itemToAdd.name, '1')) {
							// dollars
							dynTotal = dynTotal + parseFloat(itemToAdd.value) * 100;
						} else {
							// cents
							dynTotal = dynTotal + parseFloat(itemToAdd.value);
						}
					}
				}
			}
			totalLabel.innerHTML = "<B>" + formatCurrency(dynTotal) + "</B>";
		}
	}
	catch(e){
	}
	try{
		var totalCheckAmount = document.getElementById('totalCheckAmount');
		var checkAmountRemainingLabel = document.getElementById('checkAmountRemaining');
		if (totalCheckAmount != null && checkAmountRemainingLabel != null) {
			var dynTotal = 1 * totalCheckAmount.value;
			var boxes = document.paymentForm.elements;
			for(i = 0; i < boxes.length; i++) {
				var itemToAdd = boxes[i];
				if((itemToAdd.name.indexOf('RADIO_') != -1 || itemToAdd.name.indexOf('amount1') != -1 || itemToAdd.name.indexOf('amount2') != -1)
						&& itemToAdd.value != null
						&& itemToAdd.value != ''
							&& !isNaN(parseFloat(itemToAdd.value))) {
					if (endsWith(itemToAdd.name, '1')) {
						// dollars
						dynTotal = dynTotal - parseFloat(itemToAdd.value) * 100;
					} else {
						// cents
						dynTotal = dynTotal - parseFloat(itemToAdd.value);
					}
				}
			}
			checkAmountRemainingLabel.innerHTML = "<B>" + formatCurrency(dynTotal) + "</B>";
		}
	}
	catch(e){
	}
}


function startsWith (string1, string2) {
	return string1.substring(0, string2.length) == string2;
}

function endsWith (string1, string2) {
	var start = string1.length - string2.length;
	return string1.substring(start) == string2;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	if(cents < 10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
	return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}


//load the "clicked" buttons into cache
var leftCache = new Image();
leftCache.src = "/images/button_left_clicked_25.gif";

var centerCache = new Image();
centerCache.src = "/images/button_center_clicked_25.gif";

var rightCache = new Image();
rightCache.src = "/images/button_right_clicked_25.gif";

function submitForm(formName) {
	var leftButton = document.getElementById("leftButton_" + formName);
	var centerButton = document.getElementById("centerButton_" + formName);
	var rightButton = document.getElementById("rightButton_" + formName);

	// change the button text and images
	centerButton.innerHTML = "<span style='font-family: Trebuchet MS; font-size: 14px; color: #FFFFFF; font-weight: normal;'>Please Wait</span>";
	leftButton.style.backgroundImage = "url(/images/button_left_clicked_25.gif)";
	centerButton.style.backgroundImage = "url(/images/button_center_clicked_25.gif)";
	rightButton.style.backgroundImage = "url(/images/button_right_clicked_25.gif)";

	// disable the onClick and change the pointers
	leftButton.onclick = function() { return; };
	centerButton.onclick = function() { return; };
	rightButton.onclick = function() { return; };
	leftButton.style.cursor = "default";
	centerButton.style.cursor = "default";
	rightButton.style.cursor = "default";

	// submit the form
	for (var index = 0; index < document.forms.length; index++) {
		var form = document.forms[index];
		if ((form.id != null && form.id == formName) || (form.name != null && form.name == formName)) {
			form.submit();
			break;
		}
	}
}

function submitForm2(formName, paymentType) {
	document.getElementById('account').value = paymentType; 
	var leftButton = document.getElementById("leftButton_" + paymentType);
	var centerButton = document.getElementById("centerButton_" + paymentType);
	var rightButton = document.getElementById("rightButton_" + paymentType);

	// change the button text and images
	centerButton.innerHTML = "<span style='font-family: Trebuchet MS; font-size: 14px; color: #FFFFFF; font-weight: normal;'>Please Wait</span>";
	leftButton.style.backgroundImage = "url(/images/button_left_clicked_25.gif)";
	centerButton.style.backgroundImage = "url(/images/button_center_clicked_25.gif)";
	rightButton.style.backgroundImage = "url(/images/button_right_clicked_25.gif)";
	// disable the onClick and change the pointers
	leftButton.onclick = function() { return; };
	centerButton.onclick = function() { return; };
	rightButton.onclick = function() { return; };
	leftButton.style.cursor = "default";
	centerButton.style.cursor = "default";
	rightButton.style.cursor = "default";

	// submit the form
	for (var index = 0; index < document.forms.length; index++) {
		var form = document.forms[index];
		if ((form.id != null && form.id == formName) || (form.name != null && form.name == formName)) {
			form.submit();
			break;
		}
	}
}

//these 3 methods are used on the custom report
function up(current) {
	move(current, current - 1);
}
function down(current) {
	move(current, current + 1);
}
function move(current, target) {
	// swap hidden field values
	var currentField = document.getElementById('sortField' + current).value;
	var targetField = document.getElementById('sortField' + target).value;
	document.getElementById('sortField' + current).value = targetField;
	document.getElementById('sortField' + target).value = currentField;

	// swap labels
	var currentLabel = document.getElementById('label_' + current).innerHTML;
	var targetLabel = document.getElementById('label_' + target).innerHTML;
	document.getElementById('label_' + current).innerHTML = targetLabel;
	document.getElementById('label_' + target).innerHTML = currentLabel;

	// swap the dropdown values
	var currentAscending = document.getElementById('sortOrder' + current).options[0].selected
	var targetAscending = document.getElementById('sortOrder' + target).options[0].selected
	document.getElementById('sortOrder' + current).options[0].selected = targetAscending;
	document.getElementById('sortOrder' + current).options[1].selected = !targetAscending;
	document.getElementById('sortOrder' + target).options[0].selected = currentAscending;
	document.getElementById('sortOrder' + target).options[1].selected = !currentAscending;

	// swap the remove field names
	var currentRemove = document.getElementById('removeField' + current);
	var targetRemove = document.getElementById('removeField' + target);
	var removeUrl = currentRemove.href.substring(0, currentRemove.href.lastIndexOf('=') + 1);
	currentRemove.href = removeUrl + targetField;
	targetRemove.href = removeUrl + currentField;
}

function setvalue(paymentType) 
{ 
	document.getElementById('account').value = paymentType; 
}

/*
 * This disableAmounts JS function is extracted from Amounts.java Tag library
 * 
 * This function will prepopulate the first line item with the dollar and cent value passed in,
 * and if there are multiple line items, only the first line item will be populated, others will be 
 * populated with $0
 * 
 */
function disableAmounts(dollar, cent) { 
	var elements = document.getElementById('paymentForm').elements; 
	if (elements != null) { 
		for (index = 0; index < elements.length; index++) { 
			var elm = elements[index]; 
			if (elm.name == 'lineItemGroup') { 
				for (index2 = 0; index2 < elements.length; index2++) { 
					var elm2 = elements[index2]; 
					if (elm2.name.indexOf('~~~') != -1) { 
						var temp = elm2.name.substring(0, elm2.name.indexOf('~~~')); 
						if (temp == elm.value) { 
							if(elm.checked){
								if (elm2.name.indexOf('AMOUNT_0') != -1) {
									if (elm2.name.lastIndexOf('2') == (elm2.name.length - 1)) { 
										elm2.value = cent; 
									} else { 
										elm2.value = dollar; 
									} 
								} else {
									if (elm2.name.lastIndexOf('2') == (elm2.name.length - 1)) { 
										elm2.value = '00'; 
									} else { 
										elm2.value = '0'; 
									} 
								}
							} else {
								if (elm2.name.lastIndexOf('2') == (elm2.name.length - 1)) { 
									elm2.value = '00'; 
								} else { 
									elm2.value = '0'; 
								} 
							}
							elm2.disabled = !elm.checked; 
						} 
					} 
				} 
			} 
		} 
	} 
} 

function showEmailForm(from, recipients, note) {

	if (from != undefined) {
		var f = document.getElementById('from');
		f.value = from;
	}

	if (recipients != undefined) {
		var r = document.getElementById('recipients');
		r.value = recipients;
	}

	if (note != undefined) {
		var n = document.getElementById('note');
		n.value = note;
	}

	var eform = document.getElementById('eform');

	var banner = document.getElementById('banner');
	var pos = findPos(banner);
	eform.style.left = ( pos[0] + 20) + 'px';
	eform.style.top = ( pos[1] + 137 ) + 'px';

	eform.style.display = 'block';
}

function hideEmailForm() {
	var eform = document.getElementById('eform');
	eform.style.display = 'none';
}

function showThankYou() {
	var ethanks = document.getElementById('ethanks');
	var banner = document.getElementById('banner');
	var pos = findPos(banner);
	ethanks.style.left = ( pos[0] + 20) + 'px';
	ethanks.style.top = ( pos[1] + 137 ) + 'px';
	ethanks.style.display = 'block';
}

function hideThankYou() {
	var ethanks = document.getElementById('ethanks');
	ethanks.style.display = 'none';
}

function validateForm() {
	var f = document.getElementById('email_form');
	var r = document.getElementById('recipients');
	var fr = document.getElementById('from');
	var n = document.getElementById('note');
	var noError = true;
	var req = '*Required';

	colorit(r, '#000', false);
	colorit(fr, '#000', false);
	colorit(n, '#000', false);

	if (r.value == '' || r.value == req) {
		colorit(r, 'red', true);
		r.value = req;
		noError = false;
	}

	if (fr.value == '' || fr.value == req) {
		colorit(fr, 'red', true);
		fr.value = req;
		noError = false;
	}

	if (n.value == '' || n.value == req) {
		colorit(fr, 'red', true);
		n.value = req;
		noError = false;
	}

	return noError;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function colorit(o, color, bold) {
	o.style.color = color;
	if (bold) o.style.fontWeight = 'bold';
	else o.style.fontWeight = 'normal';
}



//social buttons
function share(media) {

	var shareUrl = 'http://www.rentpayment.com/sweepstakes';

	var social = {
		'facebook':'http://facebook.com/share.php?u=<url>&t=' + encodeURIComponent('Enter the RentPayment Sweepstakes, where paying rent pays you back.'),
		'twitter':'http://twitter.com/home?status=' +  encodeURIComponent('I just entered the RentPayment Sweepstakes for my chance to win $10,000! Pay your rent online for your chance to win! http://bit.ly/rpsweeps'),
		'myspace':'http://www.myspace.com/index.cfm?fuseaction=postto&t=' + encodeURIComponent('The RentPayment Sweepstakes Grand Prize $10,000 Giveaway!') + '&c=' + encodeURIComponent('Pay your rent online with RentPayment for your chance to win 1 of 10 $100 gift cards each month from now until December! One lucky winner will win the GRAND PRIZE of $10,000! Visit www.RentPayment.com/Sweepstakes for more information. RentPayment allows you to pay rent online, by phone or text message.') + '&u=<url>'
	};


	var url = social[media];
	url = url.replace('<url>', escape(shareUrl));

	var share = window.open(url, 'share_window', 'width=960,height=700,toolbar=0,menubar=0,resizable=1,scrollbars=1,location=0');
	share.focus();

}

/**
 * 
 * create a simple popup window with two buttons
 * 
 * @param titleText: the title on the title bar
 * @param popuptext: the text displayed in the popup content
 * @param leftbtntext: the text shown on the left button
 * @param leftaction: the action to be invoked when left button is clicked, it can be a url string or a javascript function
 * @param rightbtntext: the text shown on the right button
 * @param rightaction: the action to be invoked when right button is clicked, it can be a url string or a javascript function
 * @returns
 */

function createPopup(titleText, popuptext, leftbtntext, leftaction, rightbtntext, rightaction) {
	   var buttons = {};
		
	   //install actions onto each of the buttons
		  		   
	   if (!isBlank(leftbtntext)) {
		   buttons[leftbtntext] = function () {
				 if (leftaction.constructor === String) {
						//url
						window.location = leftaction;	
					} else {
		  				//invoke script
						leftaction.apply($(this));
					}
		   };
	   }

	   if (!isBlank(rightbtntext)) {
			buttons[rightbtntext] = function() {
				if (rightaction.constructor === String) {
					//url
					window.location = rightaction;
				} else {
					//invoke script
					 rightaction.apply($(this));
				}
		   };
	   }

	   var popup = $('<div></div>')
		.html(popuptext + '<br/><br/>')
		.dialog({
			autoOpen: false,
			modal: true,
			title: titleText,
			buttons: buttons
		});

	   //focus on the right button
	   popup.bind( "dialogopen", function(event, ui) {
		   popup.parent().find('Button').first().
		                                     blur().
		                                 end().
		                                 last().
		                                     focus();
		   
	   });		   
	   return popup;
	}

/**
 *  
 * utility method to show/hide a group of element based on current state.
 * If the current state is opened, then the elements passed in will be closed and vice versa.
 *
 * @param curState the current ui state, 'opened' or 'closed'
 * @param elems the elements to be toggled between show/hide
 * @param filter a function to further sift through elements, it will return true if the element should be toggled 
 *
 */
function toggleElems(curState, elems, filter) {
	// implement our own toggle since jquery.toggle() is very slow 
	function showHide($jqelem) {
    	if (curState === 'opened') {
    		$jqelem.css('display', 'none');
    	} else {
    		$jqelem.css('display', '');
    	}
	}
	
	$.each(elems, function(i, e) {
		  if (filter.apply(this,[e])) {
		  	showHide($(e));
		  }
	});

}



///////////////////////////////////
//Generic utility functions 
///////////////////////////////////

 
 function isBlank(param) {
	var blankRE = /^\s*$/;
	
	if (param == null || blankRE.test(param)) {
		return true;

	}
	
	return false;
	
}
 

/// Function: tmpl

/// Client side template parser that uses <#= #> and <# code #> expressions similar to jsp.
/// and # # code blocks for template expansion.
/// NOTE: use &amp;rsquo; for literals in text and avoid any single quote
///       attribute delimiters.
/// Parameters:    
///     str - The text of the template to expand    
///     data - javascript object to be evaluated and merged in the template text



function tmpl(str, data) {
    var err = "";
    try {
        var func = tmpl._tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            tmpl._tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err + " # >";
};

tmpl._tmplCache = {};


/*
 * Function: jsInclude
 * Dynamically include a script in the page
 * 
 * Parameters:
 * 	_dnpScript - path of script to be included
 */
function jsInclude(_dnpScript) {
	var successflag=false;

	$.ajax({
		async: false,
		type: "POST",
		url: _dnpScript,
		data: null,
		success: function() {successflag=true;},
		dataType: 'script'
	});
	return(successflag);
	
}

/*
 * Function: cloneJSON
 * creates a copy of a json data object
 * 
 * Parameters:
 *  jsondata - json object to be cloned
 */
function cloneJSON(jsondata) {
	
	try {
		  eval('JSON.stringify');

	} catch (e) {
		jsInclude('/rpcommon/js/JSON.js');
	}

	
	return eval('(' + JSON.stringify(jsondata) + ')');
}


function StringifyJSON(jsondata) {
	try {
		  eval('JSON.stringify');

	} catch (e) {
		jsInclude('/rpcommon/js/JSON.js');
	}
	
	return JSON.stringify(jsondata);
}
