var modalDialog;

function $(arg) {return dojo.query(arg);}
//init
dojo.addOnLoad(function(){

	//preload images
    dojox.image.preload(["images/nav_products_over.jpg", "images/nav_learnmore_over.jpg", "images/nav_companyinfo_over.jpg", "images/nav_contactus_over.jpg"]);

	//change Pay Now and Login links direct to:  https://www.rentpayment.com/pay/login.html?pc=WJC6ITS479
	dojo.query(".header_login a").attr("href","https://www.rentpayment.com/pay/login.html?pc=WJC6ITS479");

	//set learn_more_window form return url
	var formAction = dojo.query("#learn_more_window form").attr('action').toString()
	var urlIndex = formAction.search('url=');
	var newFormAction = formAction.substring(0,urlIndex)+"url="+escape(window.location);
	dojo.query("#learn_more_window form").attr('action',newFormAction)

	dojo.query('.dojoxFisheyeListItemLabel').forEach(function(label){
		label.innerHTML = "<img src='" + label.innerHTML + "' />";
	});

});

var current_image_number = 0;
var images = new Array();
images[0] = '../images/pic_creditcard.jpg';
images[1] = '../images/pic_ach.jpg';
images[2] = '../images/pic_services.jpg';
images[3] = '../images/pic_text.jpg';
images[4] = '../images/pic_marketing.jpg';


var texts = new Array();
texts[0] = '<font color = "#06536a">Credit Card Acceptance</font> <br><br>Experience better closing rates and increased cash flow.';
texts[1] = '<font color = "#06536a">ACH Integration</font> <br><br>Monitor payment and settlement activity 24/7 at RentPayment.com';
texts[2] = '<font color = "#06536a">Robust Services</font> <br><br>Learn more about accounting integration, check scanning and more.';
texts[3] = '<font color = "#06536a">Innovative Offerings</font> <br><br>Your residents can now pay rent right from their mobile phone!';
texts[4] = '<font color = "#06536a">Landlord Edition</font> <br><br>RentPayment Landlord is a time-tested product that will grow your business.';


var links = new Array();
links[0] = 'creditcards.html';
links[1] = 'echeck.html';
links[2] = 'services.html';
links[3] = 'rentbytext.html';
links[4] = 'marketingadvantage.html';

var popup_open = 0;
var popup_timer_id=null;
dojo.addOnLoad(function(){
	//set display for learn more Node
	dojo.query("#learn_more_window").style("display","block");

	 var n = dojo.byId("social_networking_button");
	// open the tooltip when some node is clicked:

	dojo.query(n).onmouseover(function(e){
		clearInterval(popup_timer_id);
		var tmp = dojo.query("#social_networking_button").coords();

		var top = tmp[0].y-120;
		var left = tmp[0].x - 25;
		dojo.query("#social_networking_popup").style("position","absolute");
		dojo.query("#social_networking_popup").style("top",top+'px')
		dojo.query("#social_networking_popup").style("left",left+'px');
		dojo.query("#social_networking_popup").fadeOut().stop();

		 if(popup_open==0){
			dojo.query("#social_networking_popup").style("opacity",0);
			dojo.query("#social_networking_popup").style("display","block");
			if( dojo.isIE ){
			   dojo.query("#social_networking_popup").style("opacity",1);
			}else{
				dojo.query("#social_networking_popup").fadeOut().stop();
				dojo.query("#social_networking_popup").fadeIn().play();
			}

		 }else{
			dojo.query("#social_networking_popup").style("opacity",1);
			dojo.query("#social_networking_popup").style("display","block");
		 }
		 popup_open=1;

	}).onmouseout(function(e){
		popup_timer_id = setInterval('hide_social_networking_popup()', 100);
	}).onclick(function(e){

		clearInterval(popup_timer_id);
		if(popup_open==1){
			hide_social_networking_popup();
		}else{

			dojo.query("#social_networking_popup").style("opacity",0);
			dojo.query("#social_networking_popup").style("display","block");
			dojo.query("#social_networking_popup").style("position","absolute");
			var tmp = dojo.query("#social_networking_button").coords();
			var top = tmp[0].y-120;
			var left = tmp[0].x - 25;

			if( dojo.isIE ){
			   dojo.query("#social_networking_popup").style("opacity",1);
			}else{
				dojo.query("#social_networking_popup").fadeOut().stop();
				dojo.query("#social_networking_popup").fadeIn().play();
			}

			popup_open=1;
		}
	});

	var p = dojo.byId("social_networking_popup");
	// open the tooltip when some node is clicked:

	dojo.query(p).onmouseover(function(e){

		clearInterval(popup_timer_id);

	}).onmouseout(function(){
		popup_timer_id = setInterval('hide_social_networking_popup()', 100);
	});

	modalDialog = new dijit.Dialog({
		title:'Information',
		style:'display:none;width:400px',
		content:'<button>ok</button>'
	});

	dojo.connect(modalDialog, 'hide', function(h){
		dojo.removeClass(dojo.body(), 'tundra');
		dojo.query('#learnMoreDialog .dijitDialogTitleBar').style('display','');
		dojo.query('#learnMoreDialog').addClass('dijitDialog');
	});

	dojo.connect(modalDialog, 'show', function(h){
		dojo.query('#learnMoreDialog').removeClass('dijitDialog');
		dojo.query('#learnMoreDialog .dijitDialogTitleBar').style('display','none');
		dojo.addClass(dojo.body(), 'tundra');
	});
});

function show_social_networking_popup() {

	dojo.query("#social_networking_popup").fadeIn().play();
	popup_open=1;

	return;
}
function hide_social_networking_popup() {
	if( dojo.isIE ){
	   dojo.query("#social_networking_popup").style("opacity",0);
	}else{
		dojo.query("#social_networking_popup").fadeOut().play();
	}
	popup_open=0;
	clearInterval(popup_timer_id);
}

function open_learn_more_window(){
	hide_social_networking_popup();
	dojo.query("#learn_more_window").style("display","");
	dijit.byId("learnMoreDialog").show();
}
function close_learn_more_window(){
	dijit.byId("learnMoreDialog").hide();
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days * 24 * 60 * 60 * 1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function yapnav_switch(menu_item,action) {
	var effect = 'FadeIn';
	switch (menu_item) {
		case 'ys':
			if (action =='over') {
				dojo.query("#g_ys").fadeOut(0,function() {
						dojo.query("#c_ys").fadeIn(0, function() {ys_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_ys").fadeOut(0,function() {
						dojo.query("#g_ys").fadeIn(0,function() {ys_status = 'out';});
					}
				);
			}
		break;

		case 'rp':
			if (action =='over') {
				dojo.query("#g_rp").fadeOut(0,function() {
						dojo.query("#c_rp").fadeIn(0, function() {rp_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_rp").fadeOut(0,function() {
						dojo.query("#g_rp").fadeIn(0,function() {rp_status = 'out';});
					}
				);
			}
		break;

		case 'vrp':
			if (action =='over') {
				dojo.query("#g_vrp").fadeOut(0,function() {
						dojo.query("#c_vrp").fadeIn(0, function() {vrp_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_vrp").fadeOut(0,function() {
						dojo.query("#g_vrp").fadeIn(0,function() {vrp_status = 'out';});
					}
				);
			}
		break;

		case 'srp':
			if (action =='over') {
				dojo.query("#g_srp").fadeOut(0,function() {
						dojo.query("#c_srp").fadeIn(0, function() {srp_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_srp").fadeOut(0,function() {
						dojo.query("#g_srp").fadeIn(0,function() {srp_status = 'out';});
					}
				);
			}
		break;

		case 'dp':
			if (action =='over') {
				dojo.query("#g_dp").fadeOut(0,function() {
						dojo.query("#c_dp").fadeIn(0, function() {dp_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_dp").fadeOut(0,function() {
						dojo.query("#g_dp").fadeIn(0,function() {dp_status = 'out';});
					}
				);
			}
		break;

		case 'ip':
			if (action =='over') {
				dojo.query("#g_ip").fadeOut(0,function() {
						dojo.query("#c_ip").fadeIn(0, function() {ip_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_ip").fadeOut(0,function() {
						dojo.query("#g_ip").fadeIn(0,function() {ip_status = 'out';});
					}
				);
			}
		break;

		case 'up':
			if (action =='over') {
				dojo.query("#g_up").fadeOut(0,function() {
						dojo.query("#c_up").fadeIn(0, function() {up_status = 'over';});
					}
				);
			}
			else {
				dojo.query("#c_up").fadeOut(0,function() {
						dojo.query("#g_up").fadeIn(0,function() {up_status = 'out';});
					}
				);
			}
		break;
	}
}

function reset_scrollbar() {
	//accordion links opened
	var links_opened = dojo.query("#accordion> .accordion_element:visible").length;

	if (links_opened ==0) {
		//all closed (if all links are closed, the size() will be 0

		//<show flash - hide picture>
			dojo.query("#content_left_picture").style("display","none");
			dojo.query("#content_left_flash").style("display","block");
		//</show flash - hide picture>
	}
	else {
		//<show picture - hide flash>
			dojo.query("#content_left_flash").style("display","block");
			dojo.query("#content_left_picture").style("display","none");
		//</show picture - hide flash>
	}

	scroller.reset();
	scrollbar.reset();

	//dojo.query('#accordion> .accordion_link > .accordion_element:hidden').children('div').css("background-position","0px 0px");

	if (scrollbar.disabled) {
		dojo.query("#content_right_scrollbar_container > .Scrollbar-Track").style("background","white");
		dojo.query("#content_right_scrollbar_container > .Scrollbar-Track > .Scrollbar-Handle").style("background","white");
	}
	else {
		dojo.query("#content_right_scrollbar_container > .Scrollbar-Track").style("background","url(../images/scrollbars/custom_scroll_bar.png)");
		dojo.query("#content_right_scrollbar_container > .Scrollbar-Track > .Scrollbar-Handle").style("background","url(../images/scrollbars/custom_scroller_small.jpg)");
	}

	clearInterval(scrollbar_timer_id);
}

//fisheye actions
function onImageClick(msg) {
	window.open(msg);
}

//===================================
// learnmore dialog
//===================================
function markError(id) {
	try {
		dojo.style(dojo.byId(id), 'color', 'red');
		dojo.style(dojo.byId(id), 'fontWeight', 'bold');
	} catch (e) {}
}

function trim(s) {
    return s.replace(/^\s+|\s+$/, '');
}

function validateComments(fld) {
	var error = false;
	var illegalWords = /(?:\blink\b)|(?:\bhttp\b)/i ;

	if (fld.value.match(illegalWords)) {
		markError(fld.name + "_Label");
		error = true;
	}
	return error;
}

function validatePhone(fld) {
	var error = false;
	var phoneNumber = fld.value.replace(/[\-\s()\/+]/g , '') ;  // remove punctuation and whitespace
	var phoneFilter = /^\d{10}$/ ;

    if (!phoneFilter.test(phoneNumber)) {
		markError(fld.name + "_Label");
		error = true;
	}
	return error;
}

function validateEmail(fld) {
    var error = false;
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (fld.value == "") {
        markError(fld.name + "_Label");
        error = true;
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        markError(fld.name + "_Label");
        error = true;
    } else if (fld.value.match(illegalChars)) {
        markError(fld.name + "_Label");
        error = true;
    }
    return error;
}

function validateEmpty(fld) {
    var error = false;
    if (fld.value.length == 0) {
        markError(fld.name + "_Label");
        error = true;
    }
    return error;
}

function validateUnits(fld) {
	var error = false;
	var tfld = trim(fld.value);
	var unitsFilter = /^\d+$/ ;

	if (tfld !== "") { // units is not a required field; no validation necessary if it's blank
		if (unitsFilter.test(tfld)) { // units must be all digits
			if (tfld < 1) { // number of units must be >= 1
				markError(fld.name + "_Label");
				error = true;
			}
		} else {
			markError(fld.name + "_Label");
			error = true;
		}
	}

	return error;
}


function validateFormOnSubmit(theForm) {
    var error = false;
    var emailError = false;
    var commentError = false;
    var phoneError = false;
    var unitsError = false;

    requiredFields = {'*Name':'1','*Email':'2','*Phone':'3'};

    //alert(theForm.elements.length);
    // clear out all error labels first
    for (index = 0; index < theForm.elements.length; index++) {
        var element = theForm.elements[index];
        if (element.name in requiredFields) {
            //alert(element.name + " is a " + element.type);
            if (element.type == 'text' || element.type == 'textarea' || element.type == 'select-one') {
                document.getElementById(element.name + "_Label").innerHTML = "";
            }
        }
    }

    // validate form elements
    for (index = 0; index < theForm.elements.length; index++) {
        var element = theForm.elements[index];
        try {
            if (element.name == '*Email') {
                if (validateEmail(element)) {
                    emailError = true;
                }
            } else if (element.name == '*Other') {
                 if (validateComments(element)) {
                     commentError = true;
                 }
            } else if (element.name == '*Phone') {
                 if (validatePhone(element)) {
                     phoneError = true;
                 }
            } else if (element.name == '*Units') {
                if (validateUnits(element)) {
                    unitsError = true;
                }
            } else if (element.type == 'text' || element.type == 'textarea' || element.type == 'select-one') {
                if (element.name in requiredFields) {
                    if (!error) {
                        error = validateEmpty(element);
                    } else {
                        validateEmpty(element);
                    }
                }
            }
        } catch (e) {
            continue;
        }
    }

    if (error || emailError || commentError || phoneError || unitsError) {
        var reason = "";
        if (error) {
            reason = "Please fill out all fields with a star <span style='color:red;font-weight:bold'>*</span>";
        }
        if (emailError) {
            if (error) {
                reason += " and";
            } else {
                reason += "Please";
            }
            reason += " enter a valid E-mail Address";
        }
        if (commentError) {
            if (error || emailError) {
                reason += ", and";
            } else {
                reason += "Please";
            }
            reason += " do not include the words <span style='color:red;font-weight:bold'>link</span> or <span style='color:red;font-weight:bold'>http</span> in the comments field";
        }
        if (phoneError) {
            if (error || emailError || commentError) {
                reason += ", and";
            } else {
                reason += "Please";
            }
            reason += " enter a 10-digit phone number";
        }
        if (unitsError) {
            if (error || emailError || commentError || phoneError) {
                reason += ", and";
            } else {
                reason += "Please";
            }
            reason += " enter the number of units";
        }
		modalDialog.attr('content', reason + '<p>&nbsp;</p><p><center><button onclick="modalDialog.hide();">OK</button></center></p>');
		modalDialog.show();
        return false;
    }

	close_learn_more_window();
	modalDialog.attr('content', '<center><strong>Thank you!</strong> Your message has been sent.</center>');
	modalDialog.show();

	setTimeout('submitFormFinally()', 3000);
    return false;
}

function submitFormFinally() {
	dojo.query('form').forEach(function(form){
		dojo.query(form).attr('name').forEach(function(n){
			if (n == 'learnmorepopup') {
				dojo.query(form).attr('onsubmit', function(e){return true;});
				form.submit();
			}
		});
	});
}

/* hinted form */

var HintedForm = {

	init : function(options) {

		if (options == undefined)
			options = {};

		this.hintColor = options.hintColor;
		if (this.hintColor == undefined)
			this.hintColor = '#666';
		this.textColor = options.textColor;
		if (this.textColor == undefined)
			this.textColor = '#000';

		this.requiredFields = options.requiredFields;
		this.afterSubmitCallback = options.afterSubmitCallback;
		this.beforeSubmitCallback = options.beforeSubmitCallback;
		this.onSubmitCallback = options.onSubmitCallback;

		$('.hinted_input').forEach(function(e){

			$(e).val(e.name);
			$(e).style('color',HintedForm.hintColor);

			$(e).connect('onfocus',function(f){
				if ($(e).val() == e.name)
					$(e).val('');
				$(e).style('color',HintedForm.textColor);
			}).connect('onblur',function(b){
				if ($(e).val() == '') {
					$(e).val(e.name);
					$(e).style('color',HintedForm.hintColor);
				}
			});
		});
	},

	validate : function(formId) {

		var theForm = dojo.byId(formId);
		var reason = '';
		var focusElement = null;
		var optionalElements = [];

		if (this.beforeSubmitCallback != undefined && this.beforeSubmitCallback(theForm) == false)
			return false;

		$('.hinted_input').forEach(function(e){
			dojo.style(e, 'color', this.hintColor);
		});

		for (index = 0; index < theForm.elements.length; index++) {
			var element = theForm.elements[index];
			if (element.name in this.requiredFields && (this.requiredFields[element.name](element) || element.value == element.name) ) {
				dojo.style(element, 'color', 'red');
				reason += this.requiredFields[element.name + '_Error'] + '<br/>';
				if (focusElement == null)
					focusElement = element;
			}
			else if (element.value == element.name) {
				optionalElements.push(element);
			}
		}

		if (reason != '') {
			if (focusElement != null)
				focusElement.focus();

			errorDialog.attr('content', reason + '<p>&nbsp;</p><p><center><button onclick="errorDialog.hide();">OK</button></center></p>');
			errorDialog.show();

			return false;
		}

		for (i=0;i<optionalElements.length;++i)
			optionalElements[i].value = '';

		if (this.onSubmitCallback != undefined)
			this.onSubmitCallback(theForm);

		//DEBUG
		//~ return false;

		if (this.afterSubmitCallback != undefined) {
			if (this.afterSubmitCallback.delay != undefined)
				setTimeout(this.afterSubmitCallback.callback, this.afterSubmitCallback.delay);
			else
				this.afterSubmitCallback.callback();
		}

		return true;

	}

};

/* end hinted form */
