var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];

var queryString = myScript.src.replace(/^[^\?]+\??/,'');

var params = parseQuery(queryString);
var baseUrl = params.baseUrl + '/';
var websiteBaseUrl = params.websiteBaseUrl + '/';
var website_id = params.website_id;

function parseQuery(query) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function showFlash() {
	var flash_block = $('#flash-block');
	if (flash_block) {
		flash_block.slideDown();
	}	
}
function hideFlash() {
	var flash_block = $('#flash-block');
	if (flash_block) {
		flash_block.slideUp();
	}
}
//member functions
function showFriends(id) {
	$('#popupContainer').load(baseUrl + 'ajax/member/ajax_show_friends',{id:id, website_id: website_id},
			function(str) {showPopup();});
}
function showTestimonials(id) {
	$('#popupContainer').load(baseUrl + 'ajax/member/ajax_show_testimonials',{id:id, website_id: website_id},
			function(str) {showPopup();});
}
function showSendMessage(id, subject, message, from_email, is_recipient_selection_disabled, hide_sender, is_plain_text) {
	$('#popupContainer').load(baseUrl + 'ajax/inbox/compose',{
		id: id, 
		subject: subject ? subject : '', 
	    message: message ? message : '', 
	    from_email: from_email ? from_email : '', 
	    website_id: website_id,
	    is_recipient_selection_disabled: is_recipient_selection_disabled ? 1 : 0,
	    hide_sender: hide_sender ? 1 : 0,
	    is_plain_text: is_plain_text ? 1 : 0
	}, function(str) {showPopup();});
}
function showAddFriend(id)
{
	$('#popupContainer').load(baseUrl + 'ajax/member/ajax_show_add_friend',{id:id, website_id: website_id},
			function(str) {showPopup();});
}

//event functions 
function showMembers(id) {
	$('#popupContainer').load(baseUrl + 'ajax/event/ajax_show_members',{id:id, website_id: website_id},
			function(str) {showPopup();});
}
function showGuestlist(id) {
	$('#popupContainer').load(baseUrl + 'ajax/event/ajax_show_guestlist',{id:id, website_id: website_id},
			function(str) {showPopup();});
}
function showSendEmail(id) {
    $('#popupContainer').load(baseUrl + 'ajax/event/ajax_show_send_email',{id:id, website_id: website_id},
    		function(str) {showPopup();});
}
function showDiaryAdd(id) {
    $.post(
    	baseUrl + 'ajax/event/ajax_add_to_diary',
    	{id:id, website_id: website_id},
    	function(result) {
    		$('#event-' + id).html('In the diary');
    		showInfo('Event added to diary');
    		Diary.refresh();
    	}
    );
}
function sendEmail(id)
{
	if (isValidEmailAddress($('#friend_email').val())) {
	    $.post(baseUrl + 'ajax/event/ajax_send_email',{
	    	id: id,
	        your_name: $('#your_name').val(),
	        your_email: $('#your_email').val(),
	        friend_name: $('#friend_name').val(),
	        friend_email: $('#friend_email').val(),
	        send_copy: $('#send_copy:checked').val() 
	    }, function(result) {
	    	hidePopup();
	    	showInfo(result);
	    });
	} else {
	    showInfo("Friend's e-mail address is invalid");
	}
}

//global functions
function showInfo(text, top)
{
	if(text.length == 0) {
		$('#info').html('Error!');
	}
	else {
		if(typeof(top) != 'undefined') {
			$('#info').css('top',top);
		}
		$('#info').html('<div>' + text + '</div>');
	}
	$('#info').slideDown();
	setTimeout(function() {hideInfo();}, 6000);
}

function showError(text)
{
    $('#info').html('<div>' + text + '</div>').addClass('errorBox').slideDown();
	setTimeout(function() {hideInfo();}, 10000);
}

function hideInfo()
{
	$('#info').slideUp(function() {
		$(this).removeClass('errorBox');
	});
}
function showPopup(str, disable_close) {
	var opt = {
		position : [$(window).scrollTop() + 50, null],
		close: disable_close ? false : true,
		containerCss : {
			position : 'absolute'
		}
	};

    $.requireScript(baseUrl + 'i/js/jquery/jquery.simplemodal.js', function () {
    	if (str) {
    		$.modal(str);
    	} else {
    		$('#popupContainer').modal(opt);
    	}
    });
}

function hidePopup() {
	$.modal.close();
}

$(function () {
	$('div.note-hidden:not([class=visible])').hide();
	$('div.note-hidden').each(function() {
		var note = $(this);
		note.parent().find('input[type="text"],textarea').focus(function() {
			if (note.attr('class') == 'note-hidden') {
				note.fadeIn();
			}
		});
		
		note.parent().find('input[type="text"],textarea').blur(function() {
			if (note.attr('class') == 'note-hidden') {
				note.fadeOut();
			}
		});
	});
	if ($('.tooltip')[0]) {
	    $.requireScript(baseUrl + 'i/js/jquery/jquery.tooltip.js', function () {
	    	$('.tooltip').tooltip();
	    });
	}
	if ($('.elastic')[0]) {
		$.requireScript(baseUrl + 'i/js/jquery/jquery.elastic.js', function () {
			$('.elastic').elastic();
		});
	}
});
function updateShoppingCart()
{
	$.post(baseUrl + 'ajax/shopping-cart/ajax_update_shopping_cart',{}, function(result) {
		var sum = parseInt(result, 10);
		if( !isNaN(sum) && sum > 0) {
			$('#shoppingCartSum').text('&pound;'+sum);
		}
		else {
			$('#shoppingCart').hide();
		}
    });	
}
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 showSendEmail() {
	$('#popupContainer').load(baseUrl + 'ajax/page/ajax_show_email', {
            link: document.location.href,
            title: document.title
        },
        function (a) {
            showPopup();
        }
    );
}

var group_filter_listeners = new Array();
function addGroupFilterListener(listener) {
	group_filter_listeners.push(listener);
}

function callGroupFilterListeners(groups) {
	if (groups) {
		if (!$.isArray(groups)) {
			groups = [groups];
		}
	} else {
		groups = '';
	}
	for (i = 0; i < group_filter_listeners.length; i++) {
		var listener = group_filter_listeners[i];
		window[listener](groups);
	}
}

/**
 * Script loader plugin 1.2.1
 *
 * Copyright (c) 2009 Filatov Dmitry (alpha@zforms.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

(function($) {

var scripts = [];

function loadScript(url, callback, context) {

	var script = scripts[url] || (scripts[url] = {
		loaded    : false,
		callbacks : []
	});

	if(script.loaded) {
		return callback.apply(context);
	}

	script.callbacks.push({
		fn      : callback,
		context : context
	});

	if(script.callbacks.length == 1) {
		$.ajax({
			type     : 'GET',
			url      : url,
			dataType : 'script',
			cache    : true,
			success  : function() {
				script.loaded = true;
				$.each(script.callbacks, function() {
					this.fn.apply(this.context);
				});
				script.callbacks.length = 0;
			}
		});
	}

}

$.requireScript = function(url, callback, context, options) {

	if(typeof options === 'undefined' && context && context.hasOwnProperty('parallel')) {
		options = context;
		context = window;
	}

	options = $.extend({ parallel : true }, options);

	if(!$.isArray(url)) {
		return loadScript(url, callback, context);
	}

	var counter = 0;

	// parallel loading
	if(options.parallel) {
		return $.each(url, function() {
			loadScript(this, function() {
				if(++counter == url.length) {
					callback.apply(context);
				}
			});
		});
	}

	// sequential loading
	(function() {
		if(counter == url.length) {
			return callback.apply(context);
		}
		loadScript(url[counter++], arguments.callee);
	})();

};

$.requireScript.registerLoaded = function(url) {
	$.each($.makeArray(url), function() {
		(scripts[url] || (scripts[url] = {})).loaded = true;
	});
};

})(jQuery);
