
// Cufon
Cufon.replace('div.content div.home-col h2', { fontFamily: 'MetaPlusMedium' });
Cufon.replace('div.content div.box h3');
Cufon.replace('ul.main-nav ul a', {	hover: true });
Cufon.replace('div.content div.main-title h1');
Cufon.replace('div.content div.main-title p');
Cufon.replace('div.content p.intro');
Cufon.replace('div.content div.tab h2');


$(document).ready(function () {
    VTCU.homePagePromo();
    VTCU.contentTabs();
    VTCU.textResize();
    VTCU.rollovers();
    VTCU.preloadImages(["/Images/btn_search_over.png",
                        "/Images/btn_download_over.png",
                        "/Images/btn_read_more_over.png"
                       ]);
    if (VTCU.detectMacXFF()) {
        $('div.navigation div.search input.text').addClass('ffmac');
    }
    VTCU.textareaLengthOutput();
    VTCU.dotNetFormErrorStyler();
    VTCU.slidingBox();
    VTCU.formInputMask();
    VTCU.addAddressesToggles();
    VTCU.addAdditionalInfoToggles();
	VTCU.accessibleInputValues();
	VTCU.formTooltips();
});

// VTCU User interface
var VTCU = {

    /**
     * Promo on home page
     */     
    homePagePromo: function () {
        var promo = $('div.content div.promo');
        promo.find('ul.nav').show();
        if (promo.length) {
            promo.tabs({ fx: { opacity: 'toggle', duration: 600} });
            promo.tabs('rotate', 4000, true);
        }
        if ($(".box").length) {
			var maxHeight = 0;
			$(".box").each(function() {
				
				if ($(this).height() > maxHeight) {
					maxHeight = $(this).height();
				}
			});
			$(".box .inner").attr("style", "height: " + maxHeight + "px;");
        }
    },
    
    /**
     * Content tabs
     */     
    contentTabs: function () {
        var content_tabs = $('div.content div.tabs');
        if (content_tabs.length) {
            content_tabs.tabs({ fx: { opacity: 'toggle', duration: 400} });
        }

        var $tabs = $('div.content div.tabs').tabs(); // first tab selected
        var ApplyLinks = $("a[id *= ApplyLink]");
   

        ApplyLinks.click(function () { // bind click event to link
            $tabs.tabs('select', 4); // switch to third tab
            return false;
        });
    },    
    
    /**
     * Text resize
     */         
    textResize : function(){
        
        // show text resizing links
        var $cookie_name = "fontsize";
        var originalFontSize = $("html").css("font-size");
        var fontSizeElement = $("html");
        
        // if exists load saved value, otherwise store it
        if($.cookie($cookie_name)) {
            var $getSize = $.cookie($cookie_name);
            fontSizeElement.css({fontSize : $getSize + ($getSize.indexOf("px")!=-1 ? "" : "px")}); // IE fix for double "pxpx" error
        } else {
            $.cookie($cookie_name, originalFontSize);
        }

        // Increase font size
        $("div.tools ul.font-size a.increase").bind("click", function() {
            var currentFontSize = fontSizeElement.css("font-size");
            var currentFontSizeNum = parseFloat(currentFontSize);
            var newFontSize = currentFontSizeNum + 1;
            if (newFontSize < 20) {
                fontSizeElement.css("font-size", newFontSize);
                $.cookie($cookie_name, newFontSize);
            }
            return false;   
        });
        
        // Decrease font size
        $('div.tools ul.font-size a.decrease').bind('click', function() {
            var currentFontSize = fontSizeElement.css('font-size');
            var currentFontSizeNum = parseFloat(currentFontSize);
            var newFontSize = currentFontSizeNum - 1;
            if (newFontSize > 14) {
                fontSizeElement.css('font-size', newFontSize);
                $.cookie($cookie_name, newFontSize);
            }
            return false;
        });     
    },      
    
    /**
     * Rollovers buttons
     */
    rollovers: function () {
        $('.rollover').hover(
            function () {
                $(this).attr('src', $(this).attr('src').replace(/.png/, '_over.png'));
            },
            function () {
                $(this).attr('src', $(this).attr('src').replace(/_over.png/, '.png')); 
            }
        );
     },
     
    /**
     * Preload images
     * @param {Array} images array with names of images   
     */               
    preloadImages: function (images) {
        for (var i = 0; i < images.length; i++) {
            var image = new Image();
            image.src = images[i];
        }
    },
    
    detectMacXFF: function() {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
            return true;
        }
    },
    
    textareaLengthOutput: function() {
		if ($('.formRow textarea').length > 0) {
			var fld = $('.formRow textarea');
			fld.each(function() {
				var par = $(this).parent();
				var maxLength = par.attr("MaxLength");
				var fldLength = $(this).val().length;
				if (maxLength != null && !isNaN(maxLength)) {
					maxLength = parseInt(maxLength);
					par.find("label").append('<span class="lblMaxLength">Maximum ' + maxLength + ' Chars<span></span></span>');
					var lblCharCount = par.find("label .lblMaxLength span");
					if (fldLength > 0) {
						lblCharCount.html("(Length: " + fldLength + ")");
					}				
					$(this).keyup(function() {
						fldLength = $(this).val().length;
						if (fldLength > maxLength) {
							lblCharCount.css("color", par.find(".required").css("color"));
							lblCharCount.css("font-weight", "bold");
						}
						else {
							lblCharCount.css("color", par.find(".lblMaxLength").css("color"));
							lblCharCount.css("font-weight", "normal");
						}
						if (fldLength > 0) lblCharCount.html("(Length: " + fldLength + ")");
					});
				}
			});
		}
    },
	
	dotNetFormErrorStyler: function() {
		if ($(".formErrorStyled").length > 0) {
			// http://blog.typlab.com/2009/10/mutation-events-what-happen/
			// http://help.dottoro.com/ljifcdwx.php
//			var attrModifiedWorks = false;
//			
//			var listener = function(){ 
//				attrModifiedWorks = true; 
//			};
//			document.documentElement.addEventListener("DOMAttrModified", listener, false);
//			document.documentElement.setAttribute("___TEST___", true);
//			document.documentElement.removeAttribute("___TEST___", true);
//			document.documentElement.removeEventListener("DOMAttrModified", listener, false);

//			if (!attrModifiedWorks)
//			{
//				$("span.error").each(function() {
//					//alert($(this).parent().html());
////					var attr = $(this).attr("style");
////					var eventObject = document.createEvent("MutationEvent");
////					eventObject.initMutationEvent("DOMAttrModified", true, true, attr, null, $(this).attr("style"), "style", MutationEvent.MODIFICATION);
////					$(this).dispatchEvent(eventObject);
//				});
//			}
			
			$("span.error").bind("DOMAttrModified propertychange", formErrorStyler, false);
		}		
	},
	
	slidingBox: function() {
		var menuYloc = null;
		var box = ".boxSlider";
		var topConstraint = ($('.sec-nav').length)? parseInt($('.sec-nav').css("height")) : 0;
		$(box).css("top", topConstraint + "px");
		if ($(box).length) {
			menuYloc = parseInt($(box).css("top").substring(0,$(box).css("top").indexOf("px")))
			$(window).scroll(function () { 
				offset = (menuYloc+$(document).scrollTop() <= topConstraint)? topConstraint + "px" : menuYloc+$(document).scrollTop()+"px";
				$(box).animate({top:offset},{duration:1000,queue:false});
			});
		}
	},
	
	formInputMask: function() {
		if ($(".formErrorStyled").length && $(".standardForm input:text").length) {
			$.mask.masks = $.extend($.mask.masks, { numeric: { mask: '9999999999' }, pcode: { mask: '9999'}, cash: { mask: '999,999,999,999', type: 'reverse' } });
			$("input:text").setMask(); 
		}
	},
	
	addAddressesToggles: function() {
	    if ($(".addrToggles").length > 0) {
	        // attach click event
	        $(".addrToggles input[type=radio]").click(function(e){
	            toggleAddr(this, 'event');
	        });
	        // search show the address panel by checked radio
	        $(".addrToggles input[type=radio]").each(function(e){
	            toggleAddr(this, 'load');
	        });
	    }
	},
	
	addAdditionalInfoToggles: function() {
	    if ($(".addInfoToggles").length > 0) {
	        // attach click event
	        $(".addInfoToggles input[type=radio]").click(function(e){
	            toggleAddInfo(this, 'event');
	        });
	        // search show the address panel by checked radio
	        $(".addInfoToggles input[type=radio]").each(function(e){
	            toggleAddInfo(this, 'load');
	        });
	    }
	},
	
	accessibleInputValues: function() {
		/* Accessible input values---------------- */
		$(".navigation .tools input[type=text]").each(function(){
			var id = $(this).attr("id");
			var val = $(this).val();
			if(this.value == '') this.value = val;
			$(this)
			.focus(function(){
			if(this.value == val) this.value = '';
			}).blur(function(){
			if(this.value == '') this.value = val;
			})
		});	
		
		/* Accessible input values membership form ----------- */
		$("input.auto").each(function(){
			$(this).addClass("example");
			var id = $(this).attr("id");
			var val = $(this).val();
			
			if(this.value == '') this.value = val;
			
			$(this)
				.focus(function(){
					if(this.value == val) {this.value = ''; $(this).removeClass("example"); }
				}).blur(function(){
					if(this.value == '') {this.value = val; $(this).addClass("example");}
				})
			if ($(this).val().indexOf('e.g') == -1) $(this).removeClass("example");
		});
	},
	
	formTooltips: function() {
		if ($('.toolTip').length > 0) {
			$('.toolTip').tipsy({gravity: 'sw'});
		}
	}
	
}
	
function formErrorStyler(e) {
	/* Allows styling for .net validator fields on change of value. */
	
	var feedbackStyle = "labels";
	// Exit early if IE because it throws this event lots more
	if (e.originalEvent.propertyName && e.originalEvent.propertyName != "isvalid") return;	            

	var controlToValidate = $("#" + this.controltovalidate);
	var validators = controlToValidate.attr("Validators");
	// Do not proceed if invalid validator or no control exists
	if (validators == null && controlToValidate.find("input").length == 0 && controlToValidate.find("textarea").length == 0) return;
	var isValid = true;
	if (controlToValidate.find("input").length > 0) {
		// RadioButtonList validator
		var isPrimaryOk = true;
		if (controlToValidate.attr("primaryFieldDependency") != null) { //registerExpando
			var primaryChecked = $("#" + controlToValidate.attr("primaryFieldDependency")).find("input:checked"); // locate primary field and selected value
			isPrimaryOk = (primaryChecked != null)? (primaryChecked.val() == "1") : true; // enable validation only if primary field value = 1
		}
		if (controlToValidate.find("input:checked").length == 0 && isPrimaryOk) isValid = false; // return fail if no item in radio button list is checked
	}
	else {
		$(validators).each(function() {
			if (this.isvalid !== true) {
				isValid = false;
			}
		});
	}
	
	switch (feedbackStyle) { // Error output feedback style
		case "fields":
		default:
			if (isValid) {
				controlToValidate.removeClass("error");
			} else {
				controlToValidate.addClass("error");
			}
			break;
		case "labels":
			if (isValid) {
				$(this).parent().removeClass("error");
			} else {
				$(this).parent().addClass("error");
			}
			break;
	}

   	$('span.error').each(function() {
   		if ($(this).css('display').toLowerCase()!='none' && $(this).css('visibility').toLowerCase()!='hidden') {
			$(this).parent().addClass('error');
		}
	});
	
}


function toggleAddr(sender, e) {	
	var block;
	if (sender.id.indexOf("Years3OrLonger") != -1) block = "prev";
	else if (sender.id.indexOf("SameAsResid") != -1) block = "postal";
	if ($(".addrHidden#" + block).length > 0 && block != null) {
	    if (e == 'event') {
		    if ($(sender).val() == "False") {
			    $(".addrHidden#" + block).show();
		    } else {
			    $(".addrHidden#" + block).hide();
			}
		} else if (e == 'load' && sender.checked == true) {
		    if ($(sender).val() == "False") {
		        $(".addrHidden#" + block).show();
		    } else {
		        $(".addrHidden#" + block).hide();
		    }
		}
	}	
}
function toggleAddInfo(sender, e) {
    if (e == 'event') {
	    if ($(sender).val() == "False") {
		    $(".addInfoNo").show();
		    $(".addInfoYes").hide();		    
	    } else {
		    $(".addInfoNo").hide();
		    $(".addInfoYes").show();	
		}
	} else if (e == 'load' && sender.checked == true) {
	    if ($(sender).val() == "False") {
	        $(".addInfoNo").show();
		    $(".addInfoYes").hide();		    
	    } else {
		    $(".addInfoNo").hide();
		    $(".addInfoYes").show();	
		}
	}
}

function togglePrevEmployedEducation(sender, args) {	
		var objId = sender.id.replace("cv", "rbl");
		if ($("#" + objId + " input:checked").val() == "False") {
			$(".fieldHidden[id*=relationsNo]").show();
			$(".fieldHidden[id*=relationsYes]").hide();
		}
		else if ($("#" + objId + " input:checked").val() == "True") {
			$(".fieldHidden[id*=relationsNo]").hide();
			$(".fieldHidden[id*=relationsYes]").show();
		}
		args.IsValid = true;
}

function membershipAppPopup(url) {
	return window.open(url, 'vtcuPopup', 'width=800,height=600,menubar=no,toolbar=no,addressbar=no,scrollbars=yes,statusbar=no');
}

var applicationFormConfirmMessage = "Leaving now will cancel your application. \n\nShould you wish to return to this online Membership Application, you will need to begin the application process again and re-enter all relevant fields.";

function confirmCloseApplication() {
	if (confirm(applicationFormConfirmMessage + "\n\nAre you sure you wish to cancel?")) {
		document.location.href = '/index.html';
		return false;
	}
	return;
}

window.onbeforeunload = function() { 
	if ($('body.popup .formErrorStyled, body.popup .formSummary').length) {
		return applicationFormConfirmMessage;
	}
};

window.reload = function() {
	if ($('body.popup .formErrorStyled, body.popup .formSummary').length) {
		window.onbeforeunload = null;
	}
};

$('input.submitButton').live('click', function() {
	if ($('body.popup .formErrorStyled, body.popup .formSummary').length) {
		window.onbeforeunload = null;
	}
});
