// ---------------
// Toggles visibility of the specified element.
// ---------------
function toggleVisibility(elemId) {
	var elem = document.getElementById(elemId);

	if (elem) {
		if (elem.style.display == 'none') {
			elem.style.display = 'block';
		}
		else {
			elem.style.display = 'none';
		}
	}
}

// ------------------------------------------------------------
// Changes the height of a number of elements so they are the same
// height. The input param is an array with elements-id:s.
// ------------------------------------------------------------
function adaptElementHeight(divNameArr, minHeight) {
	// This script messes up the page when it's displayed in EPi's
	// edit mode so we need this rather ugly work-around to prevent
	// the script from running when the page is viewed in edit mode.
	if (window.parent.name == 'EditPanel') {
		return;
	}
	
	var height = minHeight;
	var divArr = Array();
	
	// Loop over all the divs to get the height if the highest
	for (i = 0; i < divNameArr.length; i++) {
		divArr[i] = document.getElementById(divNameArr[i]);
		
		if (divArr[i])
		{
			// We set the height to auto to erase any previously hardcoded pixel
			// values which will otherwise prevent this function from running correctly
			// more than one time. It's useful to be able to call this function
			// again when dynamic content is displayed on the page.
			divArr[i].style.height = 'auto';
			
			if (divArr[i].clientHeight > height)
			{
				height = divArr[i].clientHeight;
			}
		}
	}

	// Set the height for all divs
	for (i = 0; i < divArr.length; i++)
	{
		if (divArr[i])
		{
			divArr[i].style.height = height + 'px';
		}
	}
}

// ------------------------------------------------------------
// Sets the height of all the children of the specified element
// to the height of the highest child.
// ------------------------------------------------------------
function adaptChildHeight(parentId) {
	// This script messes up the page when it's displayed in EPi's
	// edit mode so we need this rather ugly work-around to prevent
	// the script from running when the page is viewed in edit mode.
	if (window.parent.name == 'EditPanel')
	{
		return;
	}
	var parentElement = document.getElementById(parentId);
	if (parentElement && parentElement.childNodes.length > 2)
	{
		var maxHeight = 0;

		// Loop over all children to find the maxHeight
		for (i = 0; i < parentElement.childNodes.length; i++)
		{
			if (parentElement.childNodes[i].clientHeight > maxHeight)
			{
				maxHeight = parentElement.childNodes[i].clientHeight;
			}
		}

		// Loop over all children and set the height
		for (i = 0; i < parentElement.childNodes.length; i++)
		{
			if (parentElement.childNodes[i].style && 
				(parentElement.childNodes[i].style.clear != 'both'))
			{
				parentElement.childNodes[i].style.height = maxHeight + 'px';
			}
		}
	}
}

// ------------------------------------------------------------
// This function will fire a click event on the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return fireClickOnEnter(event, 'IdOfControlToFireClickOn');">
// ------------------------------------------------------------
function fireClickOnEnter(evt, controlId) {
	var control = document.getElementById(controlId);
	var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

	// If enter is pressed -> fire click-event on the control
	if (control && (keyCode == 13))
	{
		control.focus();
		control.click();
		return false;
	}
	else
	{
		return true;
	}
}

// ------------------------------------------------------------
// This function will fire a postbackon the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return postbackOnEnter(event, 'IdOfControlToFirePostbackOn');">
// ------------------------------------------------------------
function postbackOnEnter(evt, controlId) {
	var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

	// If enter is pressed -> do a postback
	if (keyCode == 13)
	{
		__doPostBack(controlId,'');
		return false;
	}
	else
	{
		return true;
	}
}

// ------------------------------------------------------------
// Returns the x coordinate of the specified object
// ------------------------------------------------------------
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.clientLeft)
	{
		curleft += obj.clientLeft;
	}
	return curleft;
}

// ------------------------------------------------------------
// Returns the y coordinate of the specified object
// ------------------------------------------------------------
function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.clientTop)
	{
		curtop += obj.clientTop;
	}
	return curtop;
}

// ---------------
// Returns the size of the viewport.
// ---------------
function getViewportSize() {
	size = {};
	if (window.innerHeight)
	{
		size.width  = window.innerWidth;
		size.height = window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		size.width  = document.documentElement.clientWidth;
		size.height = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		size.width  = document.body.clientWidth;
		size.height = document.body.clientHeight;
	}
	return size;
}

// ------------------------------------------------------------
// Builds an html-page for printing
// ------------------------------------------------------------
function printPage(pagename, appRoot) {
	if (!window.print)
	{
		window.status = 'No print';
		return;
	}

	// Get the main content area and other stuff we need
	var contentdiv = document.getElementById('ContentDiv');

	if (contentdiv)
	{
		var contentHtml = '<div style="padding: 0 20px 0 20px">' + contentdiv.innerHTML + '</div>';

		var beginHtml = 
			  '<html>' +
			  '<head>' +
			  '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' + 
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'styles/structure.css">' +
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'styles/main.css">' +
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'styles/units.css">' +
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'styles/print.css">' +
			  '<title>Hjärt-Lungfonden - ' + pagename + '</title>' +
			  '</head>' +
			  '<body style="margin: 10px 0px 10px 0px">';

		var footerHtml = '<div style="margin: 20px 20px 0 20px; padding: 5px 0 0 0; border-top: solid 2px #ddd" class="Bold">Hjärt-Lungfonden - Tel: 08-566 24 200 - E-post: info@hjart-lungfonden.se</div>';
		var endHtml = '</body></html>';

		var printWin = window.open('about:blank','','width=700,height=600,scrollbars=yes,toolbar=yes');
		printWin.document.open();
		printWin.document.write(beginHtml + 
								contentHtml + 
								footerHtml +
								endHtml);
		printWin.document.close();

		printWin.print();
		printWin.close();
	}
}

// ------------------------------------------------------------
// Adapt the main divs on a campaign page.
// ------------------------------------------------------------
function adaptMainCampaignDivs() {
	if (document.getElementById('iframeContainer')) {
		adaptElementHeight(new Array('LeftAreaDiv', 'RightAreaDiv'), 400);

		// Get the leftAreaDiv and set the width to 1000px
		var areaDiv = document.getElementById('LeftAreaDiv');
		if (areaDiv) {
			areaDiv.style.width = '1000px';
		}

		areaDiv = document.getElementById('RightAreaDiv');
		if (areaDiv) {
			areaDiv.style.height = '0px';
		}
	}
	else {
		adaptElementHeight(new Array('LeftAreaDiv', 'RightAreaDiv'), 400);
	}

	positionCampaignBottomImage();
}

// ------------------------------------------------------------
// Positions the bottom image for campaigns at the bottom of the page.
// ------------------------------------------------------------
function positionCampaignBottomImage() {
	var bottomImageDiv = document.getElementById('CampaignBottomImage');
	if (bottomImageDiv)
	{
		var viewSize = getViewportSize();
		var top = Math.max(document.body.clientHeight, (viewSize.height - gCampaignBottomImageHeight));
		bottomImageDiv.style.top = top + 'px';
	}
}

// ---------------
// Toggles the visibility of a campaign comment.
// ---------------
function toggleComment(id)
{
	toggleVisibility('CommentLess' + id);
	toggleVisibility('CommentMore' + id);
	adaptMainCampaignDivs();
}

// ---------------
// Updates the flash when a new value is selected in the amount drop-down
// ---------------
function updateCampaignHeartFlash(select, moduleId)
{
	var value = select.options[select.selectedIndex].value;
	var heartFlash = document.getElementById('moduleflash_' + moduleId);

	if (heartFlash)
	{
		heartFlash.sendValueToFlash(value);
	}
}




function toggleFields(el) {

	var toggleLink = $(el).find('.toggle-link');
	var dropdown = $(el).find('.toggle-dropdown');
	var field = $(el).find('.toggle-field');
	var label = $(el).find('.toggle-label');

	field.addClass('structural');

	toggleLink.click(function (e) {
		e.preventDefault();
		dropdown.toggleClass('structural');
		field.toggleClass('structural');
		if (dropdown.hasClass('structural')) {
			toggleLink.text('välj förbestämt belopp');
			label.attr('for', field.attr('id'));
			if (!field.val()) {
				//field.attr('value', '300');
			}
		} else {
			toggleLink.text('välj valfritt belopp');
			label.attr('for', dropdown.attr('id'));
			field.attr('value', '');
		}
	});

	if (field.val()) {
		toggleLink.trigger('click');
	}

}

function toggleTooltip(el) {

	var toggleLink = $(el);
	var tooltip = $(el).next('.tooltip');
	var hideButton = tooltip.find('.tooltip-close');

	tooltip.addClass('structural').css("right","-197px");

	hideButton.click(function(e) {
		e.preventDefault();
		tooltip.addClass('structural');
	});

	toggleLink.mouseenter(function(e) {
		e.preventDefault();
		tooltip.removeClass('structural');
	});

	toggleLink.mouseout(function (e) {
		e.preventDefault();
		tooltip.addClass('structural');
	});
}

$(function () {
	var togglers = $('.toggle-wrapper');
	if (togglers.length) {
		togglers.each(function () {
			toggleFields(this);
		});
	}

	var tooltips = $('.tooltip-trigger');
	if (tooltips.length) {
		tooltips.each(function () {
			toggleTooltip(this);
		});
	}

	var zipCodeField = $('.zip');

	if (zipCodeField.length) {
		zipCodeField.keyup(function () {
			var zipCodeFieldVal = zipCodeField.val().replace(/\D+/g, '');
			$.ajax({
				dataType: 'jsonp',
				url: 'http://yourmoneyisnowmymoney.com/api/zipcodes/?zipcode=' + zipCodeFieldVal,
				success: function (data) {
					if (data) {
						$('.city').val(data[0].address);
					}
				}
			});
		});
	}

	var datepickers = $('.datepicker');
	if (datepickers.length) {
		datepickers.datepicker();
	}

	// Auto expand textareas.
	var textareas = $("#form-gift textarea");

	if (textareas.length) {
		textareas.each(function () {
			if ($(this).val() == "") {
				$(this).css('height', '20px');
			} else {
				$(this).css('height', '60px');
			}
		});

		textareas.autoResize({
			// On resize:
			onResize: function () {
				//$(this).css({ opacity: 0.8 });
			},

			// After resize:
			animateCallback: function () {
				// $(this).css({ opacity: 1 });
			},

			// Quite slow animation:
			animateDuration: 300,

			// More extra space:
			extraSpace: 20
		});
	}


	// Remembrance text examples

	var memDiv = $("#memorialExamples");
	var memTrigger = $("#memorialExamplesTrigger");

	memDiv.hide();
	memTrigger.show();
	memDiv.find("a").show();

	memTrigger.click(function (e) {
		if (memDiv.css("display") == "none") {
			memDiv.slideDown(300);
			memTrigger.text("Dölj exempelhälsningar");
		} else {
			memDiv.slideUp(300);
			memTrigger.text("Visa exempelhälsningar");
		}

		return false;
	});

	$(".insert-trigger").click(function () {
		var newTxt = $(this).prev("p").text();
		$(".memorialmessage").val(newTxt).css("height", "60px");
		memDiv.hide();
		memTrigger.text("Visa exempelhälsningar");
		return false;
	});
});

