var counter = 0;
var timeStamp = (new Date()).getTime(); //unique timestamp to stop IE from caching ajax requests

$(document).ready(function() { //DOM is loaded
	//=============== SIGN OUT - MODAL CONFIRMATION DIALOG ==================//
	$("#logout").click(function(){ //the HTML that is displayed inside of #logoutBox lives in "header.gsp" 
		$("select").hide(); //hide all select elements (IE6 bugfix)
		$("#logoutBox").dialog({ //open the modal confirmation box (popup message)
			modal : true,
	        title: 'End Session',
	        resizable: false,
	        width:400,
			buttons: {
				'OK': function() {
					currHost = window.location.hostname;
					targExp = /^(localhost|dev|test|stage|www)/;
					targString = String(currHost.match(targExp));
					targString = targString.substr(0, targString.indexOf(","));
					
					if(targString == "localhost"){
						window.location.href = "https://securedev.hillspet.com:442/cas/logout?service=http://localhost:8080/hillsvet-web/signout";
					}
					else if(targString == "dev") {
						window.location.href = "https://securedev.hillspet.com:442/cas/logout?service=http://dev.hillsvet.com/signout";
					}
					else if(targString == "stage"){
						window.location.href = "https://securestage.hillspet.com/cas/logout?service=http://stage.hillsvet.com/signout";
					}
					else if(targString == "www"){
						window.location.href = "https://secure.hillspet.com/cas/logout?service=http://www.hillsvet.com/signout";
					}
					else {alert('There was a problem with the environment variable')}
				},
				'Cancel': function() {
					$(this).dialog('close');
					$("select[id!=topicInfo]").show(); //show all select elements except for <select id="topicInfo">
				}
			}
		});
	});
	//=========== HEADER SEARCH BOX ==================//
	//initVal_globalSearch();
	$("#globalSearch").validate({
		rules: {
			query: "required"
		}	
	});
	$('#hdrSearch').focus(function(){
		$(this).val('');
		$(this).css('text-align','left');
	});
});	


//============= Fixes iframe borders in IE =======================//
function ie_iframeBkgFix(iframeId){ //IE Fix for transparent background
	if(navigator.appName == "Microsoft Internet Explorer"){
		var ieFrame = parent.document.getElementById(iframeId);
		ieFrame.contentWindow.document.body.style.backgroundColor = "transparent";
    }
}


//=============== Generic function to load mvc into specified div ===========//
function mvcLoader(divName, mvcLocation){
		$('#'+divName).load('/hillsvet-web'+mvcLocation+'?timestamp='+timeStamp);
		//alert('mvcLoader function called: divName='+divName+' mvcLocation='+mvcLocation);
}


//============== GENERIC TAF EMAIL POPUP ======================//
function sendEmail(email) {
	//alert("var passed = "+email);
	//ToDo: build generic TAF functionality
}


//==== START: INITIALIZE FORM VALIDATION RULES FOR "GLOBAL SEARCH" FORM  =====================================================//
function initVal_globalSearch() {
	var options = { 
		//target: '#globalSearch',
		beforeSubmit: function(){
			alert('getting ready to submit');
		},
		success: function(data){
			alert('success');
		}
	};
	var validator = $("#globalSearch").validate({
		debug: false,
		success: "valid",
		
		rules: {
			query: "required"
		},
		messages: {
			query: "Sorry, that is not a valid search term"
		},
		submitHandler: function(form) {
			$("#globalSearch").ajaxSubmit(options);
		}
	});

}
//==== END: INITIALIZE FORM VALIDATION RULES FOR "GLOBAL SEARCH" FORM  =====================================================//


//==== START: INITIALIZE FORM VALIDATION RULES FOR "SIMPLE TAF" FORM  =====================================================//
function initVal_simpleTAF() {
	var container = $("div.errorContainer");
	var options = { 
		target: '#simpleTAF',
		beforeSubmit: function(){
			$("#simpleTAF").animate({
				opacity: 0.4
			}, 500 );
			$("#popupBox").append('<div id="loaderAnim" style="position:absolute; top:100px; left:0; width:100%; z-index:9999;"><center><br /><img src="/hillsvet-web/images/img_forms_ajaxLoader_red.gif" alt="loading" border="0" /><br /><br /><span style="color:#F20017; font-weight:bold; font-size:14px;">...transmitting data</span></center></div>');
		},
		success: function(data){
			// Check for success flag returned from the server response
			$('#loaderAnim').remove();
			$("#simpleTAF").animate({
				opacity: 1.0
			}, 100 );
			$('#simpleTAF').html('<center><h2>Thank You,<br />Your email has been sent.</h2></center>');
			setTimeout(function(){$.fn.colorbox.close();}, 10000);
		}
	};
	var validator = $("#simpleTAF").validate({
		debug: true,
		success: "valid",
		rules: {
			senderEmail: {
				required: true,
				email: true
			},
			recipientEmail: {
				required: true,
				email: true
			},
			emailSubject: "required",
			emailBody: "required"
		},
		messages: {
			senderEmail: {
				required: "Please enter your email address",
				email: "Address must be in name@domain.com format"
			},
			recipientEmail: {
				required: "Please enter the recipient email address",
				email: "Address must be in name@domain.com format"
			},
			emailSubject: "Please enter a phrase for the email subject line",
			emailBody: "Please enter your comment(s)"
		},
		/*
		showErrors: function() {
			$("#errorCount").text(validator.numberOfInvalids() + " error(s) found");
			this.defaultShowErrors();
			$('label.valid').next().css('display','none');
		},
		invalidHandler: function() {
			$(".errorContainer").css("display", "block");
			$("#errorCount").text(validator.numberOfInvalids() + " error(s) found");
		},*/
		submitHandler: function(form) {
			//$("#errorCount").text(validator.numberOfInvalids() + " error(s) found");
			$("#simpleTAF").ajaxSubmit(options);
			return false;
		}
	});
}
//==== END: INITIALIZE FORM VALIDATION RULES FOR "SIMPLE TAF" FORM  =====================================================//

// append span to end of Learn More links, so that the arrow 
// will be correctly placed in IE even when the link has multiple lines
$(document).ready(function() {
	$('.learnMoreLink').append('<span class="arrow"></span>');
 });
