;/**
 * @author		rollsd
 * @requires	jQuery
 * Base file for GY namespace
 */

GY = {
	
	/*
	 * loads an external jquery template 
	 */
	loadTemplate: function(name, callback)
	{
		$.ajax({
			url: '/js/templates/' + name + '.htm',
			dataType: 'html',
			success: function(data){
				$.template( name, data);
				if(typeof callback === "function")
				{
					callback();
				}
			}
		});
	},
	
	init: function()
	{
		
		$(document).ready( function() {
		
			// Navigation bar height to 100% of page height
			//$('.layoutTwoColumn #navColumn').height(Math.max($('#content').height()+20,$('#adColumn').height()-60));
			
			// GY Tabs
			$('.gy_tabcontent').gy_tabs();
			
			// Labelify login block
			$('#login_form #login, #login_form #password').ztInputHint({hintClass: "labelHighlight"});
			
			// Navigation 'here' class
			$('#navColumn .block-nav li a').each(function() {
				if($(this).attr('href') == window.location.href.replace('http://www.gapyear.com','').replace('http://gapyear.com','').replace('%7C','|')) {$(this).parent().addClass('here')}
			});
			
			// Slide Trigger Links
			$('.slide-trigger').click(function(event){
				event.preventDefault();
				$($(this).attr('href')).slideToggle('fast');
			});
			
			//Modal Links
			$("a.link-modal").fancybox({
				autoDimensions: false,
				transitionIn: 'fade',
				transitionOut: 'fade',
				speedIn: 600, 
				speedOut: 200, 
				modal: false,
				titlePosition: 'outside',
				showNavArrows: false,
				overlayShow: true,
				overlayOpacity: 0.9,
				scrolling:'no'
			});
			
			//Status Update Link
			$("#status-update-link").fancybox({
				autoDimensions: false,
				width:400,
				height:160,
				transitionIn: 'fade',
				transitionOut: 'fade',
				modal: false,
				showNavArrows: false,
				overlayShow: true,
				overlayOpacity: 0.9,
				scrolling:'no'
			});
			
			// Modal registration box
			$(".modal-register").fancybox({
				autoDimensions: true,
				transitionIn: 'fade',
				transitionOut: 'fade',
				modal: false,
				showNavArrows: false,
				overlayShow: true,
				overlayOpacity: 0.7,
				scrolling: 'no',
				centerOnScroll: true,
				hideOnOverlayClick: false,
				enableEscapeButton: false
			});
			
			//Search Menu
			$('#nav-search-form-drop').mouseover(
			function() {
				$('#nav-search-form-menu').slideDown('fast');
			});
			
			$('#nav-search-form-menu').hover(
			function() {
				$(this).show();
			},
			function() {
				$(this).slideUp();
			});
			
			$navSearch = $('#nav-search-form-keywords');
			if($navSearch.val() && $navSearch.val().indexOf('Search ') == 0) {
				$navSearch.addClass('unfocused');
			}
			
			$('#nav-search-form-keywords').focus(function() {
				$(this).removeClass();
				if($(this).val().indexOf('Search ') == 0) {
					$(this).val('');
				}
			});
			
			$('#nav-search-form-menu a').click(function(e) {
				_this = $(this);
				e.preventDefault();
				$('#nav-search-form-keywords').addClass('unfocused');
				$('#nav-search-form-keywords').val(_this.text()+'...');
				$('#nav-search-form-channel').val(_this.attr('name'));
				if (_this.attr('name') == 'members') {
					$('#nav-search-form').unbind();
					$('#nav-search-form').submit(function() {
						$('#nav-search-members-form').submit();
						return false;
					})
				}
				else {
					$('#nav-search-form').unbind().submit(function() {
						return true;
					});
				}
			});
			
			$('#nav-search-members-form').submit(function() {
				$('#nav-search-members-keywords').val($('#nav-search-form-keywords').val());
				return true;
			});

			// Delete a comment
			$(".comment-delete").live( 'click', function(e) {
				e.preventDefault();
				var _this = $(this);
				var commentBlock = _this.closest("li");
				var oldBg = commentBlock.css('background-color');
				var oldHTML = commentBlock.html();
				commentBlock.css({backgroundColor: 'orange'});
				var deleteUrl = '/global_misc/gy_delete_comment/' + _this.attr("href");
				if( !confirm( "Are you sure you wish to delete this comment (and all its replies)?") )
				{
					commentBlock.css({backgroundColor: oldBg });
					return false;
				}
				commentBlock.html('<br/><h3>Deleting comment .. one moment.</h3><br/><br/>');
				$.ajax({
					url: deleteUrl,
					dataType: 'json',
					success: function(data)
					{
						if(data.success)
						{
							commentBlock.html("<br/><h4>Goodbyyyyye ...</h4><br/><br/>");
							commentBlock.fadeOut( 1000 );
						}
						else
						{
							commentBlock.css({ backgroundColor: oldBg });
							commentBlock.html( oldHTML );
							alert('Sorry there was an error deleting this comment: \n'+data.error);
						}
					},
					error: function()
					{
						commentBlock.css({backgroundColor: oldBg });
						commentBlock.html( oldHTML );
						alert('An error occurred while attempting to delete this comment. The internet authorities have been informed.');
					}
				});
//				if( 'undefined' !== commentBlock ) commentBlock.css({backgroundColor: oldBg});
			});
		});
		
		$("#country_overide_form .buttons").children("img").each(function (e) {
			$(this).click(function () {
				$("#country_overide_form .buttons").children("img").removeClass("active");
				$(this).addClass("active");
				$("#currentCountry").html($(this).attr("alt"));
				$("#country").html($(this).attr("alt"));
				
				$("#country_select").submit();
			});
		});

		// Stop - cookie time! Not for paths starting with '/account'
		if( !document.location.pathname.match( /^\/?account/i ) )
		{
			GY.removeCookie( 'pageTopURL' );
			GY.setCookie( 'pageTopURL', document.location.pathname, '', '/' );
		}
	},

	getCookie: function (sKey)
	{  
		if (!sKey || !this.hasCookie(sKey)) { return null; }  
		return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));  
	},  
	/** 
	* docCookies.setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) 
	* 
	* @argument sKey (String): the name of the cookie; 
	* @argument sValue (String): the value of the cookie; 
	* @optional argument vEnd (Number, String, Date Object or null): the max-age in seconds (e.g., 31536e3 for a year) or the 
	*  expires date in GMTString format or in Date Object format; if not specified it will expire at the end of session;  
	* @optional argument sPath (String or null): e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location; 
	* @optional argument sDomain (String or null): e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not 
	* specified, defaults to the host portion of the current document location; 
	* @optional argument bSecure (Boolean or null): cookie will be transmitted only over secure protocol as https; 
	* @return undefined; 
	**/  
	setCookie: function (sKey, sValue, vEnd, sPath, sDomain, bSecure)
	{  
		if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
		var sExpires = "";
		if (vEnd) {
		  switch (typeof vEnd) {
		    case "number": sExpires = "; max-age=" + vEnd; break;
		    case "string": sExpires = "; expires=" + vEnd; break;
		    case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
			}
		}  
		document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + 
		(sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
	},  

	removeCookie: function (sKey) {  
		if (!sKey || !this.hasCookie(sKey)) { return; }
		var oExpDate = new Date();
		oExpDate.setDate(oExpDate.getDate() - 1);  
		document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";
	},

	hasCookie: function (sKey)
	{
		return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
	},
	
	initMemberFollowButtons: function()
	{
		$('#member-action-button').click(function(event) {
			event.preventDefault();
			$.ajax({
				type:		'POST',
				dataType: 	'json',
				url:		$('#member-action-button').attr('href'),
				success:	function(data){
					//console.log(data);
					var friendStatus = data.status;
					GY.updateFriendStatus (data.status, data.memberid);
				},
				error: 		function(data){
						alert('Something oops occurred. The site may be undergoing maintenance. Please try again in a couple of minutes.');
				}
			});
		});
		
		$('#member-action-loading')
			.hide()
			.ajaxStart(function() {
				$(this).show();
			})
			.ajaxStop(function() {
				$(this).hide();
			});
	},
			
	updateFriendStatus: function (status, memberid) {
				var friendURL = '/members/ajax-add/';
				switch(status) {
					case "friends":
						$('#member-action-button').removeClass().addClass('member-action-friend');
						$('#member-action-button').attr('href',friendURL + memberid + '/delete');
						GY.updateCounter('friends',1);
						break;
					case "follower":
						$('#member-action-button').removeClass().addClass('member-action-follower');
						$('#member-action-button').attr('href',friendURL + memberid);
						GY.updateCounter('friends',-1);
						break;
					case "following":
						$('#member-action-button').removeClass().addClass('member-action-following');
						$('#member-action-button').attr('href',friendURL + memberid + '/delete');
						GY.updateCounter('followers',1);
						break;
					default:
						$('#member-action-button').removeClass().addClass('member-action-follow');
						$('#member-action-button').attr('href',friendURL + memberid);
						GY.updateCounter('followers',-1);
						break;
				}
	},

	updateCounter: function(counter, amount) {
		$('#member-stats-'+counter).html(parseInt($('#member-stats-'+counter).html())+amount);
	}, 	
	
	/*
	 *  Cleans a string (eg a title) to into a clean url string.
	 *  Lower-case, remove non alpha-numeric characters, and replace spaces with hyphens.
	 *  @param string str
	 *  @returns string
	 */
	 urlString: function(str)
	 {
	 	if(typeof str!='undefined')
	 	{
	 		return str.toLowerCase().replace(/[^a-z0-9_ -]/g,'').replace(/\s+/g,'-');
	 	}
	 	else
	 	{
	 		return '';
	 	}
	 },
	 
	newsletterSubscribe: function(firstName, lastName, email)
	 {	 	
		$.ajax({
            type: 'POST',
			url: "/info/index.php/leadCapture/save",
            dataType:"html",
            data:"Email="+encodeURIComponent(email)+"&FirstName="+encodeURIComponent(firstName)+"&LastName="+encodeURIComponent(lastName)+"&cr=&formid=1002&kw=&lpId=1004&lpurl=http%3A%2F%2Finfo.gapyear.com%2FProductEnquiry1.html%3Fcr%3D%7Bcreative%7D%26kw%3D%7Bkeyword%7D&_marketo_comments=&_mkt_disp=return&_mkt_trk=id:857-DSK-853&token:_mch-gapyear.com-1323403616293-89081&retURL=&returnURL=&searchstr=&subId=15&NewsletterType=monthly-weekly",
            success:function(response){               
                //console.log("User signed up successfully!!!");
            },
            error:function (xhr, ajaxOptions, thrownError){
                //console.log(xhr.status);
                //console.log(thrownError);
            }    
        });
	 },
	 
	 /**
	  * This method allows for the deletion of entries from the front end.
	  * params:
	  *	 deleteUrl - URL to hit
	  *  type - entry, comment
	  *  confirmMessage - Prompt to get assurance
	  *  onDelete - optional callback function on delete success
	  *  onFail - optional callback in event of failure
	  */
	 deleteEntry: function( options )
	 {
		if(typeof options!= 'undefined' &&  typeof options.deleteUrl == 'string')
		{
			var deleteUrl = options.deleteUrl;
			var type = options.type || 'entry';
			var confirmMessage = options.confirmMessage || 'Are you sure you want to delete this gallery and its contents?';
			var onDelete = options.onDelete || null;
			var onFail = options.onFail || null;
		}
		else
		{
			return;
		}
		
		var confirmDelete = confirm( confirmMessage );
		
		if(confirmDelete)
		{
			$.fancybox(				
			'<div id="gyDelete"><span class="loading">Deleting '+ type +'...</span></div>',
			{
				'autoDimensions'	: true,
				'width'         	: 240,
				'height'  : 100,
				'autoScale' : false,
				'showTitle': false
			});

			$.ajax({
				url: deleteUrl,
				dataType: 'json',
				success: function(data)
				{
					if(data.success)
					{
						$.fancybox.close();
						if(typeof onDelete == 'function' ) onDelete();
					}
					else
					{
						$('#gyDelete').html('Sorry there was an error deleting this '+ type +': \n'+data.error);
						if(typeof onFail == 'function' ) onFail();
					}
				},
				error: function(data)
				{
					if(data.success)
					{
						$.fancybox.close();
						if(typeof onDelete == 'function' ) onDelete();
					}
					$('#gyDelete').html('Sorry there was an error when attempting to delete this '+ type +'.');
					if(typeof onFail == 'function' ) onFail();
				}
			});
		}
	 },

	 conLog: function() {
	 	if( !arguments.length ) return;
	 	for( var i = 0; i < arguments.length; i++ )
	 	{
	 		if(window.console&&window.console.log){window.console.log(arguments[i]);}
	 	}
	 }
	 
};


GY.init();


