/**
 * @author dt.john
 */
function homeSliderInit(){
	var homeSlider = $('#home_feature_tour');
	var slideCount = homeSlider.children().length;
	var tourWidth = (slideCount * 894)+"px";
	var widthInc = 894;
	var sliderPos;
	$('#home_feature_tour').css("width",tourWidth);
	$('a.tourNext').click(function(){
		sliderPos = homeSlider.position();
		homeSlider.animate({
			left: '-'+(widthInc - sliderPos.left)+'px'
		}, "slow");
				
		return false;
	});
	$('a.tourPrevious').click(function(){
		sliderPos = homeSlider.position();
		homeSlider.animate({
			left: (widthInc + sliderPos.left)+'px'
		}, "slow");
		
		return false;
	});
}
function faqToggle(){
	$('.faqQuestion').click(function(){
		var hrefVal = $(this).attr('href');
		answerBlock = $('#'+hrefVal.substring(1));
		if($('#'+hrefVal.substring(1)+'_question').hasClass('active')){
			answerBlock.slideUp('slow');
			$('#'+hrefVal.substring(1)+'_question').removeClass('active');
		}else{
			answerBlock.slideDown('slow');
			$('#'+hrefVal.substring(1)+'_question').addClass('active');
		}
		return false;
	});
	$('.faqAnswer').hide();
}
function textResize(){
	if($.cookie("textSize")!=""){
		$('#text_size a').removeClass('active');
		if($.cookie("textSize")=="Normal"){
			$('body').css("font-size","62.5%");
			$('#text_size_normal').addClass('active');
		}else if($.cookie("textSize")=="Large"){
			$('body').css("font-size","80.5%");
			$('#text_size_large').addClass('active');
		}else if($.cookie("textSize")=="Extra Large"){
			$('body').css("font-size","100.5%");
			$('#text_size_extra-large').addClass('active');
		}
	}	
	$('#text_size_normal').click(function(){
		$('body').css("font-size","62.5%");
		$('#text_size a').removeClass('active');
		$(this).addClass('active');
		$.cookie("textSize","Normal",{expires:7});
		CufonFonts.init();
		return false;
	});
	$('#text_size_large').click(function(){
		$('body').css("font-size","80.5%");
		$('#text_size a').removeClass('active');
		$(this).addClass('active');
		$.cookie("textSize","Large",{expires:7});
		CufonFonts.init();
		return false;
	});
	$('#text_size_extra-large').click(function(){
		$('body').css("font-size","100.5%");
		$('#text_size a').removeClass('active');
		$(this).addClass('active');
		$.cookie("textSize","Extra Large",{expires:7});
		CufonFonts.init();
		return false;
	});
}
function liveChat(){
	$('a[href="#live-chat"]').attr("href","http://livechat.boldchat.com/aid/8076127112123836175/bc.chat?cwdid=8699080480951181330")
	.click(function(){
		window.open('http://livechat.boldchat.com/aid/8076127112123836175/bc.chat?cwdid=8699080480951181330&amp;url=' + escape(document.location.href), 'Chat625293680804874013', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=640,height=480');
		return false;
	});
	
}
function loginError(){
	$('#login_form').submit(function(){
		$('#existingCustomerError').fadeIn("fast",function(){
			setTimeout("$('#existingCustomerError').fadeOut(3000)",3000);
		});
		
		return false;
	});
}
//Calculator AJAX Requests
function quickCalc(){
	$('#quick_calc_form').submit(function(e){
		if($('#quick_calc_form input.required[value!=""]').length == $('#quick_calc_form input.required').length){
			if($('#input_zip').attr("value").length < 5){
				alert('Zip requires 5 digits')
			}else{
				loadingImage = '<img src="/images/legacy_loading_spinner.gif" alt="Loading" id="ajax-loading" />';
				$('#quick_calc_form').before(loadingImage).addClass('processing');
				if ($('#calc_total').css("display") != "none") {
					$('#calc_total').addClass('processing');
				}
				$.post(
					'/code_behind/soap_fixed.php',
					$('#quick_calc_form').serialize(),
					function(response){
						if(response.message == null){
							$('#calc_total_number').text('$'+response.cashAvailable);
							if($('#calc_total').css("display") == "none"){
								$('#calc_total').fadeIn("slow");
							}							
							$('#quick_calc_form, #calc_total').removeClass('processing');
							$('#ajax-loading').remove();
							Cufon.replace('#calc_total_number',{fontFamily: 'aller'});
						}else{
							$('#age_error').fadeIn('slow');
							var autoFade = setTimeout("$('#age_error').fadeOut('slow')",5000);
							$('#age_error a').click(function(e){
								$('#age_error').fadeOut('slow');
								return false;
							});
							$('#quick_calc_form').removeClass('processing');
							$('#ajax-loading').remove();
						}					
					},
					'json'
				);
			}
		}else{
			alert('All fields are required, please fill out all 3 fields');
		}
		$.post(
			'/code_behind/session_builder.php',
			$('#quick_calc_form').serialize()
		);
		e.preventDefault();
		return false;
	});
}
function sessionBuilder(id){
	$('#'+id+' input.submit').click(function(e){
		e.preventDefault();
		if(window.validateForms[id].validate()){
			$.post(
				'/code_behind/session_builder.php',
				$('#'+id).serialize(),
				function(response){
					if(response.built == "working"){
						if(id == "reverse_mortgage_form"){
							$.post("/widget_processor.php",$('#reverse_mortgage_form').serialize(),function(){
								$('#'+id).submit();
							});
						} else {
							$('#'+id).submit();
						}
					}else{
						alert('Oops - something went wrong')
					}					
				},
				'json'
			);
		}
	});
}
function submitRVCalculator(){
	$('#reverse_mortgage form.rvCalculator input.submit').click(function(e){
		e.preventDefault();
		if(window.validateForms['reverse_mortgage_form'].validate()){
			$('#reverse_mortgage form.rvCalculator').submit();
		}
	});
}
function convertAge(){
	currentTime = new Date();
	currentYear = currentTime.getFullYear();
	if($('#input_age1').attr('value') != ""){
		age1 = $('#input_age1').attr('value');
		birthyear1 = (currentYear - age1);
		$('#birthdate_borrower').attr('value', "1/1/"+birthyear1);
	}
	if($('#input_age2').attr('value') != ""){
		age2 = $('#input_age2').attr('value');
		birthyear2 = (currentYear - age2);
		$('#birthdate_coborrower').attr('value', "1/1/"+birthyear2);
	}
	$('#input_age1').keyup(function(){
		age1 = $('#input_age1').attr('value');
		birthyear1 = (currentYear - age1);
		$('#birthdate_borrower').attr('value', "1/1/"+birthyear1);
	});
	$('#input_age2').keyup(function(){
		age2 = $('#input_age2').attr('value');
		birthyear2 = (currentYear - age2);
		$('#birthdate_coborrower').attr('value', "1/1/"+birthyear2);
	});
}
/**
 * Cufon font initializer
 * @author					Dave Shepard
 * @version					0.2
 * @required libraries:		JQuery 1.3.2, Cufon 
 * 
 * Usage:
 *     $(document).ready(function(){
 *         CufonFonts.init();
 *     });
 * 
 * An initialization script for Simo Kinnunen's Cufon font replacer available 
 * at: http://wiki.github.com/sorccu/cufon. This is an independent
 * script from Cufon and is unsupported by Sorccu.
 * 
 * Fill the CufonInitializer.fonts array with objects containing the font CSS
 * name and the elements to apply the font to in the CufonInitializer.fonts.elements
 * array. Elements to apply the font to will take any CSS font reference method
 * supported by Prototype.
 */
var CufonFonts = {
	fonts: [
		{
			name: 'aller',
			elements: [
				'.homeFeaturedSubtitle p',
				'.homeFeaturedSubtitle li',
				'#text_size li.first',
				'#text_size li a',
				'#loan_comparison ul li',
				'#lc_get_started',
				'#whats_new_list li a',
				'.resultLabel',
				'.noteText',
				'.homeFeaturedBody ul li',
				'.faqQuestion',
				'.blogCategory',
				'#pros',
				'#cons',
				'.thePoint h5',
				'#go_to_calc .note',
				'#go_to_quote .note',
				'#calc_total h6',
				'#calc_total_number'
			]
		},
		{
			name: 'aller',
			elements: [
				'#main_nav a'
			],
			options: {
				textShadow : '#ffffff 1px 1px'
			}
		},
		{
			name: 'aller-light',
			elements: [
				'#calculator_wrapper h4',
				'#chat_time',
				'#home_content h4',
				'#content_container_inner h4',
				'.branchInfo li',
				'#page_text p',
				'.buttonNote',
				'.postData'
			]
		},
		{
			name: 'new-aster',
			elements: [
				'#calculator_wrapper h3',
				'#live_chat_cta h3',
				'#home_content h3',
				'#customer_login h4',
				'.footerNav h6',
				'#content_container_inner h3',
				'#content_container_inner h2',
				'#sidebar h3',
				'.resultValue'
			]
		},
		{
			name: 'new-aster',
			elements: [
				'#live_chat',
				'#phone_cta'
			],
			options: {
				textShadow : '#314c58 1px 1px'
			}
		},
		{
			name: 'new-aster',
			elements: [
				'.homeFeaturedTitle',
				'#page_title'
			],
			options: {
				textShadow : '#d5d6bc 1px 1px'
			}
		}
	],
	init: function(){
		for(i = 0; i < this.fonts.length; i++) {
			var f = this.fonts[i];
			var existingElements = [];
			for (ie = 0; ie < f.elements.length; ie++) {
				var cfe = f.elements[ie];
				if ($(cfe).length > 0) {
					existingElements.push(cfe);
				}
			}
			var cufonOptions = {
				fontFamily : f.name
			}
			if(f.options != undefined){
				var optionKeys = $.keys(f.options);
				for(w=0 ; w < optionKeys.length ; w++){
					cufonOptions[optionKeys[w]] = f.options[optionKeys[w]];
				}
			}
			if(existingElements.length > 0){
				Cufon.replace(existingElements.join(","),cufonOptions);
			}
		}
	}
}

$.extend({
	keys: function(obj){
		var a = [];
		$.each(obj, function(k){ a.push(k) });
		return a;
	}
});
/**
 * DOM Utilies Object for handling basic DOM actions
 * @author					Dave Shepard
 * @version					1.0
 * @required libraries:		JQuery 1.3.2 or later
 * 
 * Usage:
 *     $(document).ready(function(){
 *     		DOMUtilities.init();
 *     });
 *     
 * Can be initialized via the init(); method to apply to entire <body> or
 * a scope can be passed to limit the initialization to the child elements
 * of a particular element. Individual methods can als be called and passed
 * a scope.
 */
var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$(locality+' a[rel*="external"]').attr("target","_blank");
	},
	inputAutoClear: function(locality){
		$(locality+' input.clearField').focus(function(){
			if(this.defaultValue == this.value) this.value='';
		}).blur(function(){
			if(this.value == '') this.value = this.defaultValue;
		});
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver')
			.mouseover(function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).mouseout(function(){
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if(this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.","_i.");
				}
			}).filter("input").mousedown(function(){
				this.src = this.src.replace("_o.","_a.");
			}).mouseup(function(){
				this.src = this.src.replace("_a.","_i.");
			});
	},
	init: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}
var FancyBox = {
	boxen: function(){
		if ($(".fancyBox").length) {
			$("a.fancyBox").fancybox({
				'hideOnContentClick': true,
				'zoomSpeedIn': 300,
				'zoomSpeedOut': 300,
				'overlayOpacity': 0.8,
				'overlayColor' : '#000000'
			});
		}
		if($('a.videoFancyBox').length){
			$('a.videoFancyBox').fancybox({
				'frameWidth' : 500,
				'frameHeight' : 370,
				'hideOnContentClick': false,
				'zoomSpeedIn': 300,
				'zoomSpeedOut': 300,
				'overlayOpacity': 0.8,
				'overlayColor' : '#000000'
			});
		}
	},	
	init: function(){
		this.boxen();	
	}
}

var EditQuote = {
    init: function(){
        if($('#monetary_info a.changeInfo').length){
            $('#monetary_info a.changeInfo').click(function(e){
                e.preventDefault();
                $('#monetary_info').removeClass('edit');
                return false;
            });
        }
        if($('#borrower_info a.changeInfo').length){
            $('#borrower_info a.changeInfo').click(function(e){
                e.preventDefault();
                $('#borrower_info').removeClass('edit');
                return false;
            });
        }
    }
};

var FormatNumbers = {
    addCommas: function(nStr){
        nStr = nStr.replace(',','');
        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;
    },
    init: function(){
        if($('input#input_worth').length){
            $('input#input_worth').keyup(function(){
                var theValue = $(this).val();
                var formattedVal = FormatNumbers.addCommas(theValue);
                $('input#input_worth').val(formattedVal);
            });            
        }
        if($('input#input_how_much').length){
            $('input#input_how_much').keyup(function(){
                var theValue = $(this).val();
                var formattedVal = FormatNumbers.addCommas(theValue);
                $('input#input_how_much').val(formattedVal);
            });
        }
        if($('input#input_property_value').length){
            $('input#input_property_value').keyup(function(){
                var theValue = $(this).val();
                var formattedVal = FormatNumbers.addCommas(theValue);
                $('input#input_property_value').val(formattedVal);
            });
        }
        if($('form#quick_calc_form').length){
            $('form#quick_calc_form').submit(function(e){
                var formattedVal = FormatNumbers.addCommas($('input#input_property_value').val());
                $('input#input_property_value').val(formattedVal);
            });
        }
        if($('form#reverse_mortgage_form').length){
           $('form#reverse_mortgage_form').submit(function(e){
                var formattedValWorth = FormatNumbers.addCommas($('input#input_worth').val());
                var formattedValLien = FormatNumbers.addCommas($('input#input_how_much').val());
                $('input#input_worth').val(formattedValWorth);
                $('input#input_how_much').val(formattedValLien);
           }); 
        }
    }
};


$(document).ready(function(){
	window.validateForms = {};
	DOMUtilities.init();
 	CufonFonts.init();
	if ($('#home_feature_tour').length) homeSliderInit();
	if ($('#faq_list').length) faqToggle();
	if ($('#text_size').length) textResize();
	if ($('a[href="#live-chat"]').length) liveChat();
	if ($('#quick_calc_form').length) quickCalc();
	//if($('#reverse_mortgage_form').length) reverseCalc();
	if ($('#reverse_mortgage_form').length) window.validateForms['reverse_mortgage_form'] = new FormValidator('reverse_mortgage_form',{'00N8000000468WC': 'Zip Required', '00N80000003bxNQ': 'Property Value Required', liens: 'Amount Required', 'age1': 'Age Required',first_name: 'First Name Required', last_name: 'Last Name Required', phone: 'Phone Number Required', street: 'Address Required', city: 'City Required', state: 'State Required', zip: 'Zip Required' });
	if ($('#contact_form').length) window.validateForms['contact_form'] = new FormValidator('contact_form',{first_name: 'First Name Required', last_name: 'Last Name Required', email: 'Email Address Required', '00N800000045xel': 'Comment Required'});
	if ($('#comment_form').length) window.validateForms['comment_form'] = new FormValidator('comment_form',{name: 'Name Required', email: 'Email Address Required',comment: 'Comment Required'});
	if ($('#login_form').length > 0) loginError();
	if ($('#reverse_mortgage form.requestQuote').length) {
		convertAge();
		sessionBuilder('reverse_mortgage_form');
	}
	if ($('#reverse_mortgage form.rvCalculator').length) submitRVCalculator();
	if ($('#contact_form').length) sessionBuilder('contact_form');
	FancyBox.init();
    EditQuote.init();
    FormatNumbers.init();
 });
