/***
Script
-----------------------------------------------
domain7.com
file:		/js/script.css
firm:		FH Canada
date:		2009
***/

// SET SOME GLOBAL VARIABLES
var dialog_h=500;
var dialog_w=750;
var is_live = true;
var like_url= 'http://site.fhcanada.com/like';
var is_ns = true;
var fbapp='153712657985049';
if (window.location.href.match(/site\.fhcanada\.org|fhsandbox\.domain7\.com/)) {
	is_ns=false;
}
if (window.location.href.match(/fh\.domain7\.com|sandbox/)) {
	fbapp='141534279212987';
	is_live=false;
	like_url= 'http://fhsandbox.domain7.com/like';
}

/* Suckerfish - main navigation dropdown
----------------------------------------------- */
sfHover = function() {
	try {
		var sfEls = document.getElementById("mainnav").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			};
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			};
		}
	} catch (e) {
		//do nothing
	}
};
if (window.attachEvent) { window.attachEvent("onload", sfHover); }

/**
 * Allow Getting URL var by its name
 * var byName = $.getUrlVar('name')
 */
jQuery.extend({
	getUrlVars: function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++){
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 *
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// NOTE Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		return false;
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie !== '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

/*
 * Show loading spinner.
 */
function showLoading(title){
	if (this.title) {
		title=this.title;
	}
	$('.ui-dialog-content').dialog('close');
	$('#loading').append(' ' + title) ;
	$('#loading').show();
	return true;
}

/*
 * Generic popover
 */
function make_dialog(id, title){
	$('#' + id ).dialog({
		'title': ' ' + title,
		'width':dialog_w,
		'height':dialog_h,
		'modal':true,
		'autoOpen':true
	});
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function commitToPrayer() {
	if (is_logged_in == false) {
		alert('Please sign in to receive this badge');
		return false;
	}
	showLoading('Signing you up for prayer updates');
	window.location.href = '/commit-to-prayer/community_name/'. this_community_name;
}

function tellAFriend() {
	if (is_logged_in == false) {
		alert('Please sign in to receive this badge');
		return false;
	}
	var valid_form = true;
	if (!isValidEmailAddress($('#TellAFriendEmailAddress').val())){
		valid_form = false;
	}
	if ($('#TellAFriendRecipientName').val() == '') {
		valid_form = false;
	}
	if (valid_form == true) {
		var url = '/send-email/community_id/' + this_community_id + '/toAddress/';
		url += $('#TellAFriendEmailAddress').val() + '/body/';
		url += $('#TellAFriendMessage').val() +'/community_name/' + this_community_name + '/recipient_name/';
		url += $('#TellAFriendRecipientName').val();

		showLoading('Sending your message');

		window.location.href = url;
	} else {
		alert('Please make sure you have entered a valid email address and a recipent name');
	}
}

function send_message(id, name){
	$('#itemid').val(id);
	$('#messgeform').dialog({
		'title': 'Message To: '+ name,
		'width':dialog_w,
		'height':dialog_h,
		'modal':true,
		'autoOpen':true,
		'open': function(event,ui){
			$('#custrecord_message_body').rte({
				content_css_url: '/css/rte.css',
				media_url: '/images/rte/'
			});
		},
		'close': function(event,ui){
			var content = $('iframe#custrecord_message_body').contents().find('body').html();
			$('textarea#custrecord_message_body').val(content);
			$('iframe#custrecord_message_body').remove();
		},
		'buttons':{
			'Send': function(){
				$('#sendMessage').submit();
				showLoading('Sending Message');
			}
		}
	});
}

function child_detail(id){
//populate the first time
	if (0 == $('#child' + id ).html().length) {
		$('#child' + id ).load(
			'/child-detail/itemid/'+id,
			{},
			function(responseText, textStatus, XMLHttpRequest) {
				$('#child' + id ).dialog({
					'width':dialog_w,
					'height':dialog_h,
					'modal':true,
					'autoOpen':true
				});
			}
		);
	} else {
		$('#child' + id ).dialog({
			'width':dialog_w,
			'height':dialog_h,
			'modal':true,
			'autoOpen':true
		});
	}
}

function badgeDescription(id) {
	$('.active-popup').hide();
	$('.active-popup').removeClass('active-popup');
	$('#' + id).show();
	$('#' + id).addClass('active-popup');
	$('.' + id).blur();
}

function navScroll(dir) {
	var nextButton = document.getElementById('nextButton');
	var prevButton = document.getElementById('prevButton');

	if (dir == 'right') {
		$('#badge-slider').animate({left: '-654px'},500);
		prevButton.style.opacity = '1';
		prevButton.style.filter = 'alpha(opacity=100)';
		nextButton.style.opacity = '0.4';
		nextButton.style.filter = 'alpha(opacity=40)';
		nextButton.blur();
	}
	if (dir == 'left') {
		$('#badge-slider').animate({left: '0px'},500);
		nextButton.style.opacity = '1';
		nextButton.style.filter = 'alpha(opacity=100)';
		prevButton.style.opacity = '0.4';
		prevButton.style.filter = 'alpha(opacity=40)';
		prevButton.blur();
	}
	return false;
}

function leave_group(id){
	$('#confirm_remove').empty();
	$('#confirm_remove').append('Are you sure you wish to leave this group?');
	$('#confirm_remove').dialog({
		'title': 'Leave Group',
		'resizable': false,
		'height':140,
		'modal': true,
		'buttons': {
			'Leave Group': function() {
				window.location='/group-leave/group_id/' + id ;
			},
			'Cancel': function() {
				$(this).dialog('close');
			}
		}
	});
}

function leave_community(id){
	$('#confirm_remove').empty();
	$('#confirm_remove').append('Are you sure you wish to leave this community?');
	$('#confirm_remove').dialog({
		'title': 'Leave Community',
		'resizable': false,
		'height':140,
		'modal': true,
		'buttons': {
			'Leave Community': function() {
				window.location='/community_leave/community_id/' + id ;
			},
			'Cancel': function() {
				$(this).dialog('close');
			}
		}
	});
}

function add_update(){
	$('#myOnPageContentAddUpdate').dialog({
		'title': 'Add an Update',
		'width':dialog_w,
		'height':dialog_h,
		'modal':true,
		'autoOpen':true,
		'open': function(event,ui){
			$('#custrecord_posts_body').rte({
				content_css_url: '/css/rte.css',
				media_url: '/images/rte/'
			});
		},
		'close': function(event,ui){
			var content = $('iframe#custrecord_posts_body').contents().find('body').html();
			$('textarea#custrecord_posts_body').val(content);
			$('iframe#custrecord_posts_body').remove();
		},
		'buttons':{
			'Post Update': function(){
				$('#addUpdate').submit();
				showLoading('Add an Update');
			}
		}
	});

}
function message_group(){
	$('#group-message-popover').dialog({
		'title': 'Send Your Group a Message',
		'width':dialog_w,
		'height':dialog_h,
		'modal':true,
		'autoOpen':true,
		'open': function(event,ui){
			$('#message-body').rte({
				content_css_url: '/css/rte.css',
				media_url: '/images/rte/'
			});
		},
		'close': function(event,ui){
			var content = $('iframe#message-body').contents().find('body').html();
			$('textarea#message-body').val(content);
			$('iframe#message-body').remove();
		},
		'buttons':{
			'Message Group': function(){
				$('#groupMessage').submit();
				showLoading('Sending Group Message');
			}
		}
	});
}

function sandbox_rewrites() {
	$("a").each(function() {
		this.href = this.href.replace(/(forms|checkout|system)\.netsuite\.com/,
			"$1.sandbox.netsuite.com");
		this.href = this.href.replace(/http:\/\/www\.fhcanada\.org/,
			"http://fh.domain7.com");
		this.href = this.href.replace(/http:\/\/site\.fhcanada\.org/,
			"http://fhsandbox.domain7.com");
	});
	$("iframe").each(function() {
		this.src = this.src.replace(/(forms|checkout|system)\.netsuite\.com/,
			"$1.sandbox.netsuite.com");
	});
	$("form").each(function() {
		this.action = this.action.replace(/(forms|checkout|system)\.netsuite\.com/,
			"$1.sandbox.netsuite.com");
	});
}

jQuery(document).ready(function() {
	$('a[title]').bind('click', showLoading);
	if (! is_live){
		sandbox_rewrites();
	}
});

