
//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var DivPopupStatus = 0;
var DivPopupRequesterObject = null;

//loading popup with jQuery magic!
function DivPopupShow(ObjectToShow){
	//loads popup only if it is disabled
	if(DivPopupStatus == 0)
	{
		// If object to show is not already known - use the provided one.
		if(DivPopupRequesterObject == null)
			DivPopupRequesterObject = ObjectToShow;
		
		$("div.DisplayEmailFields").show();
		$("div.DisplayEmailConfirmation").hide();
		$("div.DisplayEmailError").hide();

		$("#DivPopupBackground").css({
			"opacity": "0.7"
		});
		$("#DivPopupBackground").fadeIn("slow");
		$("#DivPopupRequester").fadeIn("slow");
		DivPopupStatus = 1;

		if (DivPopupRequesterObject != null) {
//		    DivPopupRequesterObject.css('backgroundColor', 'Green');
		    DivPopupRequesterObject.css('display', '');
		    $("#DivPopupRequester").html('');
		    $("#DivPopupRequester").append(DivPopupRequesterObject);

			// Center the popup with css
			DivPopupCenter();
		}
	}
	return false;
}

function DivPopupShowDirect(ObjectToShow, ObjectToMakeVisible){
	//loads popup only if it is disabled
	if(DivPopupStatus == 0)
	{
		// If object to show is not already known - use the provided one.
		if(DivPopupRequesterObject == null)
			DivPopupRequesterObject = ObjectToShow;
		
		$('div.DisplayEmailFields').hide();
		$('div.DisplayEmailConfirmation').hide();
		$('div.DisplayEmailError').hide();

		alert('Innan show()');
		ObjectToMakeVisible.show();

		$("#DivPopupBackground").css({
			"opacity": "0.7"
		});
		$("#DivPopupBackground").show();
		$("#DivPopupRequester").show();
		DivPopupStatus = 1;

		if (DivPopupRequesterObject != null) {
//		    DivPopupRequesterObject.css('backgroundColor', 'Green');
		    DivPopupRequesterObject.css('display', '');
		    $("#DivPopupRequester").html('');
		    $("#DivPopupRequester").append(DivPopupRequesterObject);

			// Center the popup with css
			DivPopupCenter();
		}
	}
	return false;
}

//disabling popup with jQuery magic!
function DivPopupHide(){
	//disables popup only if it is enabled
	if(DivPopupStatus == 1){
		$("#DivPopupBackground").fadeOut("slow");
		$("#DivPopupRequester").fadeOut("slow");
		DivPopupStatus = 0;
	}
}

//centering popup
function DivPopupCenter(){
	//request data for centering
	var popupHeight = $("#DivPopupRequester").height();
	var popupWidth = $("#DivPopupRequester").width();
    var windowWidth = document.documentElement.clientWidth;
    if(isNaN(windowWidth) || windowWidth == 0)
		windowWidth = $(document).width();
	var windowHeight = document.documentElement.clientHeight;
    if(isNaN(windowHeight) || windowHeight == 0)
		windowHeight = $(document).height();
	//centering
	$("#DivPopupRequester").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});

	//only need force for IE6
	$("#DivPopupBackground").css({
		"height": windowHeight
	});
}

$(document).ready(function() {

    // Add event for clicking on button to bring up requester.
//    $('input[name="CancelPopupButton"]').click(function() {
//        // Load popup
//        DivPopupShow($("div#requester"));
//        // Center popup with css
//        DivPopupCenter();
//    });

    $(window).resize(function() {
        // Centering popup with css
        DivPopupCenter();
    });

    // Add event for closing the requester.
    if($(".DivPopupRequesterClose") != null)
	    $(".DivPopupRequesterClose").click(function() {
		    DivPopupHide();
		});
    // Click out event!
    $("#DivPopupBackground").click(function() {
        DivPopupHide();
    });
//    //Press Escape event!
//    $(document).keypress(function(e) {
//        alert('Keycode: ' + e.keyCode);
//        if (e.keyCode == 27 && popupStatus == 1) {
//            disablePopup();
//        }
//    });
    $(document).keydown(function(e) {
        if (e.keyCode == 27 && DivPopupStatus == 1) {
            DivPopupHide();
        }
    });
});

function SendTheMailMessage(txtMyName, txtMyMail, txtFriendsName, txtFriendsMail, txtMessage, txtPageLink)
{
	var friendsName = $('input#' + txtFriendsName).val();
	var friendsEmail = $('input#' + txtFriendsMail).val();
	var myName = $('input#' + txtMyName).val();
	var myEmail = $('input#' + txtMyMail).val();
	var message = $('textarea#' + txtMessage).val();
	var pageLink = $('input#' + txtPageLink).val();


	var validationSummary = '';
	
	// Friends name.
	if(friendsName == '')
		validationSummary += 'Din v&auml;ns namn m&aring;ste anges.<br />';
	
	// ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
	// Friends email address.
	if(friendsEmail == '')
		validationSummary += 'Din v&auml;ns epostadress m&aring;ste anges.<br />';
	else if(friendsEmail.indexOf('@') <= 0)
		validationSummary += 'Din v&auml;ns epostadress m&aring;ste vara korrekt angiven.<br />';
	
	// Users name.
	if(myName == '')
		validationSummary += 'Ditt namn m&aring;ste anges.<br />';
	
	// Users email address.
	if(myEmail == '')
		validationSummary += 'Din epostadress m&aring;ste anges.<br />';
	else if(myEmail.indexOf('@') <= 0)
		validationSummary += 'Din epostadress m&aring;ste vara korrekt angiven.<br />';
	
	// Display validation summary HTML to user.
	$('span#ValidationSummaryPopup').html(validationSummary);
	
	// If no validation errors then submit form. Otherwise exit.
	if(validationSummary != '')
		return;



	var mailparams =
		'?FriendsName=' + escape(htmlEncode(friendsName)) +
		'&FriendsEmail=' + escape(friendsEmail) +
		'&MyName=' + escape(htmlEncode(myName)) +
		'&MyEmail=' + escape(myEmail) +
		'&Message=' + escape(htmlEncode(message)) +
		'&PageLink=' + escape(pageLink);

	jQuery.ajax({
		cache: false,
		type: "GET",
		url: "/templates/TellAFriendMailHandler.ashx" + mailparams,
		contentType: "text/plain; charset=utf-8",
		data: "{}",
		dataType: "text",
		success: function(msg, textStatus){
			$('div#DisplayEmailFields').hide();
			$('div#DisplayEmailConfirmation').show();
			// Rensa inmatningsfält.
			$('input#' + txtFriendsName).val('');
			$('input#' + txtFriendsMail).val('');
			$('input#' + txtMyName).val('');
			$('input#' + txtMyMail).val('');
			$('textarea#' + txtMessage).val('');
		},
		error: function (request, textStatus, errorThrown) {
			// Typically only one of textStatus or errorThrown will have info.
			$('div#DisplayEmailFields').hide();
			$('div#DisplayEmailError').show();
			$('div#MailResult').html('Resultat: ' + textStatus + '. ' + errorThrown + '.');
		}
	});
}

























/*HTMLEncode - Encode HTML special characters.Copyright (c) 2006 Thomas Peri, http://www.tumuski.com/Permission is hereby granted, free of charge, to any person obtaining acopy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:The Software shall be used for Good, not Evil.The above copyright notice and this permission notice shall be includedin all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*//** * HTML-Encode the supplied input *  * Parameters: * * (String)  source    The text to be encoded. *  * (boolean) display   The output is intended for display. * *                     If true: *                     * Tabs will be expanded to the number of spaces  *                       indicated by the 'tabs' argument. *                     * Line breaks will be converted to <br />. * *                     If false: *                     * Tabs and linebreaks get turned into &#____; *                       entities just like all other control characters. * * (integer) tabs      The number of spaces to expand tabs to.  (Ignored  *                     when the 'display' parameter evaluates to false.) * * v 0.3 - January 4, 2006 */function htmlEncode(source, display, tabs){	function special(source)	{		var result = '';		for (var i = 0; i < source.length; i++)		{			var c = source.charAt(i);			if (c < ' ' || c > '~')			{				c = '&#' + c.charCodeAt() + ';';			}			result += c;		}		return result;	}		function format(source)	{		// Use only integer part of tabs, and default to 4		tabs = (tabs >= 0) ? Math.floor(tabs) : 4;				// split along line breaks		var lines = source.split(/\r\n|\r|\n/);				// expand tabs		for (var i = 0; i < lines.length; i++)		{			var line = lines[i];			var newLine = '';			for (var p = 0; p < line.length; p++)			{				var c = line.charAt(p);				if (c === '\t')				{					var spaces = tabs - (newLine.length % tabs);					for (var s = 0; s < spaces; s++)					{						newLine += ' ';					}				}				else				{					newLine += c;				}			}			// If a line starts or ends with a space, it evaporates in html			// unless it's an nbsp.			newLine = newLine.replace(/(^ )|( $)/g, '&nbsp;');			lines[i] = newLine;		}				// re-join lines		var result = lines.join('<br />');				// break up contiguous blocks of spaces with non-breaking spaces		result = result.replace(/  /g, ' &nbsp;');				// tada!		return result;	}	var result = source;		// ampersands (&)	result = result.replace(/\&/g,'&amp;');	// less-thans (<)	result = result.replace(/\</g,'&lt;');	// greater-thans (>)	result = result.replace(/\>/g,'&gt;');		if (display)	{		// format for display		result = format(result);	}	else	{		// Replace quotes if it isn't for display,		// since it's probably going in an html attribute.		result = result.replace(new RegExp('"','g'), '&quot;');	}	// special characters	result = special(result);		// tada!	return result;}