

/*
----------------------------------------------------------------------------------------------- 
DOM MANIPULATION                                                                                      	
----------------------------------------------------------------------------------------------- 
*/

$(document).ready(function(){
	
/* TOGGLE HELP MESSAGES ------------------------------------------------------------------------ */	
// Get some nice buttons :)
	$('#help_button').click(function(){
		$(this).toggleClass('help_active');
		$(".inline_flash_msg").slideToggle();
	});	
	
/* HIDE YUKKY FORM SUBMITS --------------------------------------------------------------------- */	
// Get some nice buttons :)
	$('.submitbutton').hide();
	

/* CLOSE WINDOW -------------------------------------------------------------------------------- */	
	// Close window	
	$("#window_close").click(function () {$.fancyWindow('#flash_window','hide');});



/* LOGIN --------------------------------------------------------------------------------------- */	
// Show login window


if ($("#login_form").length) {
	$(".login_link").click(function (e) {
		$('.fancy_window').hide();
		$.fancyWindow('#login_window','show');
		
	});
	} else {
		$(".login_link").attr("href","/login");
	
	}
	
// Hide & Reset login window
	$("#login_cancel").click(function () {
		$.fancyWindow('#login_window','hide');
		$("#loginError").hide();
        $("#login").removeClass('inputWithErrors');
        $("#passwordError").hide();
        $("#password").removeClass('inputWithErrors');
	});
	
// Submit Login and hide window	
	$("#login_submit").click(function () {
	
	if (!$.checkValidEmail($("#login").val()))  {
        	$("#login").addClass('inputWithErrors');
        	$("#loginError").slideDown();
            var field1 = false;
        } else { 
        	var field1 = true;
        	$("#loginError").slideUp('fast');
        	$("#login").removeClass('inputWithErrors');
        }
        
        if ($("#password").val() =='') {
          	$("#password").addClass('inputWithErrors');
          	$("#passwordError").slideDown();
         	var field2 = false;
        } else { 
        	var field2 = true;
        	$("#passwordError").slideUp('fast');
        	$("#password").removeClass('inputWithErrors');
        }


		if (field1 && field2) {	
			$.fancyWindow('#login_window','hide');
			// submit form
			$("#login_form").submit();
		}
		
		
		

	});  

/* FORGOT PASSWORD ----------------------------------------------------------------------------- */	
// Show forgot password window
	$(".forgot_password").click(function () {
		$('.fancy_window').hide();	
		$.fancyWindow('#forgot_password_window','show');
	});

// Hide & Reset  forgot password window
	$("#forgot_password_cancel").click(function () {
		$.fancyWindow('#forgot_password_window','hide');
		$("#forgotEmailError").hide();
        $("#email").removeClass('inputWithErrors');
	});

// Submit forgot password and hide window	
	$("#forgot_password_submit").click(function () {
	
	
	if (!$.checkValidEmail($("#email").val()))  {
        	$("#email").addClass('inputWithErrors');
        	$("#forgotEmailError").slideDown();
            var field1 = false;
        } else { 
        	var field1 = true;
        	$("#forgotEmailError").slideUp('fast');
        	$("#email").removeClass('inputWithErrors');

        }

		if (field1) {	
			$.fancyWindow('#forgot_password_window','hide');
			// submit form
			$("#forgot_password_form").submit();
		}
	}); 


/* Join Us INVITE ---------------------------------------------------------------------------------- */	
// Show Join Us invite window

function registerWindow(status){
	if (status=="show"){
		$("#register_form").slideDown();
		$("#news_and_yourtown").slideUp();
	} 
	
	if (status=="hide") {
		$("#register_form").slideUp();
		$("#news_and_yourtown").slideDown();
	
	}

}

	if ($("#register_form").length) {
		$(".register_link").toggle(
			function () {
				registerWindow("show");
			},function (){
				registerWindow("hide");
			}
		);
	} 	


	
// Hide & Reset Join Us invite window
	$("#register_cancel").click(function () {
		registerWindow("hide");        
		$("#emailError").hide();
        $("#invitation_recipient_email").removeClass('inputWithErrors');		
        $("#firstNameError").hide();
        $("#invitation_recipient_first_name").removeClass('inputWithErrors');		
        $("#surnameError").hide();
        $("#invitation_recipient_surname").removeClass('inputWithErrors');		
	});
// Submit and hide window	
	$("#register_submit").click(function () {
	
		var invitation_recipient_email = $("#invitation_recipient_email").val()
		var invitation_recipient_first_name = $("#invitation_recipient_first_name").val()
		var invitation_recipient_surname = $("#invitation_recipient_surname").val()
		
		//var invitation_recipient_email = invitation_recipient_email.replace(/^\s|\s$/g, '');
        
        
        if (!$.checkValidEmail(invitation_recipient_email))  {
        	$("#invitation_recipient_email").addClass('inputWithErrors');
        	$("#emailError").slideDown();
            var field1 = false;
        } else { 
        	var field1 = true;
        	$("#emailError").slideUp('fast');
        	$("#invitation_recipient_email").removeClass('inputWithErrors');

        }
         
        if (invitation_recipient_first_name =='') {
          	$("#invitation_recipient_first_name").addClass('inputWithErrors');
          	$("#firstNameError").slideDown();
         	var field2 = false;
        } else { 
        	var field2 = true;
        	$("#firstNameError").slideUp('fast');
        	$("#invitation_recipient_first_name").removeClass('inputWithErrors');
        }

       
        if (invitation_recipient_surname =='') {
          	$("#invitation_recipient_surname").addClass('inputWithErrors');
          	$("#surnameError").slideDown();
        	var field3 = false;
        } else { 
        	var field3 = true;
        	$("#surnameError").slideUp('fast');
        	$("#invitation_recipient_surname").removeClass('inputWithErrors');
        }

         
        if (field1 && field2 && field3) {		
			registerWindow("hide");
			// submit form
			//$("#new_invitation").submit();
			
			var invitations_url 			= $("#new_invitation").attr("action");
			var invitation_recipient_email 	= $("#invitation_recipient_email").attr("value");
			var invitation_recipient_first_name	= $("#invitation_recipient_first_name").attr("value");
			var invitation_recipient_surname 	= $("#invitation_recipient_surname").attr("value");
			var AUTH_TOKEN 	= encodeURIComponent($("#authenticity_token").attr("value"));
			
			$.ajax({
   				type: "POST",
   				url: invitations_url,
   				dataType: "json",
   				data: "authenticity_token="+AUTH_TOKEN+"&invitation[recipient_email]="+invitation_recipient_email+"&invitation[recipient_first_name]="+invitation_recipient_first_name+"&invitation[recipient_surname]="+invitation_recipient_surname,
   				success: function(data){
					showAppMessage(data.appmessage.title,data.appmessage.message,data.appmessage.link_action,data.appmessage.link_text);
   				}
   			});	
		}
	});



function showAppMessage(title,message,link_action,link_text){

	if (title !="") {$("#appmessage_title").empty().append(title).show();}
	if (message !="") {$("#appmessage_message").empty().append(message).show();}
	if (link_text !="" && link_action !="") {$("#appmessage_link").addClass(link_action).empty().append(link_text).show();}

	$("#cta_message").fadeOut("fast", function(){$("#appmessage").fadeIn();})
	
	$(".login_link").click(function () {
		$('.fancy_window').hide();
		$.fancyWindow('#login_window','show');
	});
	
	$(".register_link").toggle(
		function () {
			registerWindow("show");
		},function (){
			registerWindow("hide");
	}
	);
	
	$("#appmessage_link").click(function(){
		$("#invitation_recipient_email").attr("value","");
		$("#invitation_recipient_first_name").attr("value","");
		$("#invitation_recipient_surname").attr("value","");
		$("#appmessage").fadeOut();
		$("#cta_message").slideDown(); 
	});
	
}

/* SIGNUP --------------------------------------------------------------------------------------- */	
// Submit and hide Signup window	//
$("#member_screen_name").keyup(function(){
if ( ($("#member_screen_name").val()=='') || ($("#member_screen_name").val().length <6)) {
          	$("#member_screen_name").addClass('inputWithErrors');
          	$("#signupScreennameError").slideDown();
        	var field4 = false;
        } else { 
        	var field4 = true;
        	$("#signupScreennameError").slideUp('fast');
        	$("#member_screen_name").removeClass('inputWithErrors');
        }
});


$("#member_password").keyup(function(){

        if ( ($("#member_password").val() =='') || ($("#member_password").val().length <8)) {
          	$("#member_password").addClass('inputWithErrors');
          	$("#signupPasswordError").slideDown();
        	var field1 = false;
        } else { 
        	var field1 = true;
        	$("#signupPasswordError").slideUp('fast');
        	$("#member_password").removeClass('inputWithErrors');
        }
});

$("#member_password_confirmation").keyup(function(){

        if ( ($("#member_password_confirmation").val() =='') || ($("#member_password_confirmation").val() !=$("#member_password").val())) {
          	$("#member_password_confirmation").addClass('inputWithErrors');
          	$("#signupPasswordConfirmError").slideDown();
        	var field2 = false;
        } else { 
        	var field2 = true;
        	$("#signupPasswordConfirmError").slideUp('fast');
        	$("#member_password_confirmation").removeClass('inputWithErrors');
        }
});


	$("#signup_submit").click(function () {
	
	
       
        if ( ($("#member_password").val() =='') || ($("#member_password").val().length <8)) {
          	$("#member_password").addClass('inputWithErrors');
          	$("#signupPasswordError").slideDown();
        	var field1 = false;
        } else { 
        	var field1 = true;
        	$("#signupPasswordError").slideUp('fast');
        	$("#member_password").removeClass('inputWithErrors');
        }

        if ( ($("#member_password_confirmation").val() =='') || ($("#member_password_confirmation").val() !=$("#member_password").val())) {
          	$("#member_password_confirmation").addClass('inputWithErrors');
          	$("#signupPasswordConfirmError").slideDown();
        	var field2 = false;
        } else { 
        	var field2 = true;
        	$("#signupPasswordConfirmError").slideUp('fast');
        	$("#member_password_confirmation").removeClass('inputWithErrors');
        }

        if ( !$("#terms_agreed").attr("checked") ) {
          	$("#terms_agreed").addClass('inputWithErrors');
          	$("#signupTandCError").slideDown();
        	var field3 = false;
        } else { 
        	var field3 = true;
        	$("#signupTandCError").slideUp('fast');
        	$("#terms_agreed").removeClass('inputWithErrors');
        }
        
        if ( ($("#member_screen_name").val()=='') || ($("#member_screen_name").val().length <6)) {
          	$("#member_screen_name").addClass('inputWithErrors');
          	$("#signupScreennameError").slideDown();
        	var field4 = false;
        } else { 
        	var field4 = true;
        	$("#signupScreennameError").slideUp('fast');
        	$("#member_screen_nameE").removeClass('inputWithErrors');
        }



		if ((field1 && field2 && field3) && (field1==field2)) {		
			$.fancyWindow('#signup_window','hide');
			// submit form
			//var dataString = $("#login_form").serialize(); 
			$("#new_member").submit();
		}
	});

// Cancel and hide Signup window	
	$("#signup_cancel").click(function () {
		$.fancyWindow('#signup_window','hide');
	});

// Cancel and hide fancy Dialog	
	$("#dialog_cancel").click(function () {
		$.fancyDialog('#app_msg_dialog','hide');
	});
	
/* PRELOAD IMAGES -------------------------------------------------------------------------------- */	
	
	$.preloadImages("../images/window_button.png", "../images/window_back.png");
	// fetaures fadeFX
	var features = fadeFX();
	features.init();

  
});



/*
----------------------------------------------------------------------------------------------- 
FUNCTIONS                                                                                      	
----------------------------------------------------------------------------------------------- 
*/


/* SOCIAL BOOKMARKS -------------------------------------------------------------------------------- */	

// Replace with your URL here
var image_dir="/images/socialbookmark_icons/";

function add_bookmark_button(icon, name, url) {
  document.write('<span class="social_bookmark_button" id="socialAddButton-' + icon + '"><a href="' + url + '" title="Add to ' + name +'" class="with-tooltip"><img src="' + image_dir + '/' + icon + '.png" alt="' + name + ' icon" /></a></span> ');
}

function add_twitter_button(icon, name, url) {
  document.write('<span class="social_bookmark_button" id="socialAddButton-' + icon + '"><a href="' + url + '" title="Tweet this" class="with-tooltip"><img src="' + image_dir + '/' + icon + '.png" alt="' + name + ' icon" /></a></span> ');
}

function social_bookmarks() {
  var title = encodeURIComponent(document.title);
  var url = encodeURIComponent(document.URL);
  
  document.write('<div class="social_bookmarks_widget rounded">');
  add_bookmark_button('delicious', 'del.icio.us', 'http://del.icio.us/post?url=' + url + '&amp;title=' + title);
  add_bookmark_button('digg', 'digg', 'http://digg.com/submit?phase=2&amp;url=' + url + '&amp;title=' + title);
  add_bookmark_button('newsvine', 'Newsvine', 'http://www.newsvine.com/_tools/seed&amp;save?u=' + url + '&amp;h=' + title);
  add_bookmark_button('reddit', 'reddit', 'http://reddit.com/submit?url=' + url + '&amp;title=' + title);
  add_bookmark_button('yahoo', 'Yahoo! My Web', 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' + url + '&amp;t=' + title);
  add_bookmark_button('google', 'Google', 'http://www.google.com/bookmarks/mark?op=add&bkmk=' + url + '&amp;title=' + title);
  add_twitter_button('twitter', 'Tweet This', 'http://twitter.com/home?status=Currently reading ' + title + ' at ' + url);  
  document.write('</div>');
}






/* PRELOAD IMAGES -------------------------------------------------------------------------------- */	

// jquery image preload plugin
// http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery
jQuery.preloadImages = function(){
	for(var i = 0; i<arguments.length; i++){
		jQuery("<img>").attr("src", arguments[i]);
	}
}


/* FANCY WINDOWS --------------------------------------------------------------------------------- */	

// Hide show windows
jQuery.fancyWindow = function(windowID,on_off){
	if (on_off =="show") {
		$("#modalshade").fadeIn(200,function(){$(windowID).fadeIn(200,function(){return true;});});
	}
	if (on_off =="hide") {
		$(windowID).fadeOut(50, function(){$("#modalshade").fadeOut(100,function(){return true;});});
		return true;
	}
}

/* FANCY DIALOG --------------------------------------------------------------------------------- */	

// Hide show windows
jQuery.fancyDialog = function(windowID,on_off,message_title,message_body,url,authToken){
	if (on_off =="show") {
		$(windowID).find(".message_title").empty().prepend(message_title);
		$(windowID).find(".message_body").empty().prepend(message_body);
		$(windowID).fadeIn(200,function(){return true;});
		$("#dialog_form").attr("action","/"+url);
		$("#authenticity_token").attr("value",authToken);
		$("#dialog_submit").click(function () {
			$("#dialog_form").submit();
		});
	}
	if (on_off =="hide") {
		$(windowID).find(".message_title").empty()
		$(windowID).find(".message_body").empty()	
		$(windowID).fadeOut(200,function(){return true;});
		showfinishdialog = false;
		return true;
	}
}


/* FANCY MSG DIALOG --------------------------------------------------------------------------------- */	

// Hide show windows
jQuery.fancyMsgDialog = function(windowID,on_off,message_title,message_body){
	if (on_off =="show") {
		$(windowID).find(".message_title").empty().prepend(message_title);
		$(windowID).find(".message_body").empty().prepend(message_body);
		$(windowID).fadeIn(200,function(){return true;});
		

	}
	if (on_off =="hide") {
		$(windowID).find(".message_title").empty()
		$(windowID).find(".message_body").empty()	
		$(windowID).fadeOut(200,function(){return true;});
		return true;
	}
}





/* QUESTIONNAIRE SLIDERS ------------------------------------------------------------------------- */	
// render out eco bahaviour question sliders.
jQuery.renderEcoBehaiviourSlider = function(ecoBehaviourID,memberScore,authToken){

		$("#q"+ecoBehaviourID+"_slider").slider({
    		    handle: '.ui-slider-handle',
    		    min: 0,
    		    max: 100,
    		    animate: false,
    		    startValue: memberScore, 
    		    stop: function (e, ui) {
    		    	$.ajax({
    		    	
   						type: "PUT",
   						url: "/member_eco_behaviours/"+ecoBehaviourID,
   						data: "authenticity_token="+encodeURIComponent(authToken)+"&member_eco_behaviour[raw_score]="+ui.value,
   						success: function(msg){
     						// change bubble back to normal state
     						//$('#slider-bubble'+ecoBehaviourID).css('background-position','bottom');
     						$('#questions_throbber').fadeOut('slow');
     						$('#q'+ecoBehaviourID).removeClass('question-unanswered').addClass('question');	
							update_progress_meter();
   						}
 					});
    		    },  slide: function(e, ui) {
    		    
    		    	$('#slider-bubble'+ecoBehaviourID).text(Math.abs(Math.round(ui.value))+"%");
    		    	$('#q1a_icon'+ecoBehaviourID).css("opacity", ui.value/100+0.05);
    		    	$('#q1b_icon'+ecoBehaviourID).css("opacity", Math.abs(ui.value-100)/100+0.05);
    		    	
    		    	$('#questions_throbber').show();
    		    }
    		});
			
			
			// move bubble to correct position and stick a number in it
			$('#slider-bubble'+ecoBehaviourID).css('left', Math.round(memberScore * 1.32)).text(Math.abs(Math.round(memberScore))+"%");
			
			// set opacity of icons
			$('#q1a_icon'+ecoBehaviourID).css("opacity", memberScore/100+0.05);    	
    		$('#q1b_icon'+ecoBehaviourID).css("opacity", Math.abs(memberScore-100)/100+0.05);
    		
    		// move slider to inital position
    		$("#q"+ecoBehaviourID+"_slider .ui-slider-handle").css("left", Math.round(memberScore * 1.32));

}


/* FADEFX ------------------------------------------------------------------------- */	
// fadeFX function
var fadeFX = function() {
	var me = this;
	var args = arguments;
	var self = {
		c: {
			navItems: '.column, .column_active, .lastcolumn, .lastcolumn_active',
			navSpeed: ($.browser.safari ? 500: 250),
			snOpeningSpeed: ($.browser.safari ? 400: 250),
			snOpeningTimeout: 150,
			snClosingSpeed: function() {
				if (self.subnavHovered()) return 123450;
				return 150
			},
			snClosingTimeout: 700
		},
		init: function() {
			//$('.bg', this.c.navItems).css({
			//	'opacity': 0
			//});
			this.initHoverFades()
		},
		subnavHovered: function() {
			var hovered = false;
			$(self.c.navItems).each(function() {
				if (this.hovered) hovered = true
			});
			return hovered
		},
		initHoverFades: function() {
			//$('#navigation .bg').css('opacity', 0);
			$(self.c.navItems).hover(function() {
				self.fadeNavIn.apply(this)
			},
			function() {
				var el = this;
				setTimeout(function() {
					if (!el.open) self.fadeNavOut.apply(el)
				},
				10)
			})
		},
		fadeNavIn: function() {
			$('.bg', this).stop().animate({
				'opacity': 1
			},
			self.c.navSpeed)
		},
		fadeNavOut: function() {
			$('.bg', this).stop().animate({
				'opacity': 0
			},
			self.c.navSpeed)
		},
		initSubmenus: function() {
			$(this.c.navItems).hover(function() {
				$(self.c.navItems).not(this).each(function() {
					self.fadeNavOut.apply(this);
				});
				this.hovered = true;
				var el = this;
				self.fadeNavIn.apply(el);
			},
			function() {
				this.hovered = false;
				var el = this;
				if (!el.open) self.fadeNavOut.apply(el);
			})
		}
	};
	
	return self;
};



function getURLParam(param)
{
  param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+param+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}




jQuery.hsvToRgb = function (h,s,v) {  
     var s = s / 100,  
          v = v / 100;  
   
     var hi = Math.floor((h/60) % 6);  
     var f = (h / 60) - hi;  
     var p = v * (1 - s);  
     var q = v * (1 - f * s);  
     var t = v * (1 - (1 - f) * s);  
   
     var rgb = [];  
   
     switch (hi) {  
         case 0: rgb = [v,t,p];break;  
         case 1: rgb = [q,v,p];break;  
         case 2: rgb = [p,v,t];break;  
         case 3: rgb = [p,q,v];break;  
         case 4: rgb = [t,p,v];break;  
         case 5: rgb = [v,p,q];break;  
     }  
   
     var r = Math.min(255, Math.round(rgb[0]*256)),  
         g = Math.min(255, Math.round(rgb[1]*256)),  
         b = Math.min(255, Math.round(rgb[2]*256));  
   
     return [r,g,b];  
 } 
 
 
 
/* CHECK EMAIL ------------------------------------------------------------------------- */	
// render out eco bahaviour question sliders.
jQuery.checkValidEmail = function(emailToCheck){

	var reg = /^([A-Za-z0-9_\-\.-])+\@([A-Za-z0-9_\-\.-])+\.([A-Za-z]{2,4})$/;
   	if(reg.test(emailToCheck) == false) {
      // Invalid email
    	return false;
        } else { 
        // Valid email
        return true;
    }
}



/* Ajaxify links :) ------------------------------------------------------------------------- */	

jQuery(document).ready(function() {




  jQuery('a.get').livequery('click', function() {
    var link = jQuery(this);
    $.get(link.attr('href'), function(data) {
      if (link.attr('ajaxtarget'))
        jQuery(link.attr('ajaxtarget')).html(data);
    });
    return false;
  }).attr("rel", "nofollow");
 
  jQuery('a.post').livequery('click', function() {
    var link = jQuery(this);
    $.post(jQuery(this).attr('href'), "_method=post", function(data) {
      if (link.attr('ajaxtarget'))
        jQuery(link.attr('ajaxtarget')).html(data);
    });
    return false;
  }).attr("rel", "nofollow");
 
  jQuery('a.put').livequery('click', function() {
    var link = jQuery(this);
    $.post(jQuery(this).attr('href'), "_method=put", function(data) {
      if (link.attr('ajaxtarget'))
        jQuery(link.attr('ajaxtarget')).html(data);
    });
    return false;
  }).attr("rel", "nofollow");
 
  jQuery('a.delete').livequery('click', function() {
    var link = jQuery(this);
    $.post(jQuery(this).attr('href'), "_method=delete", function(data) {
      if (link.attr('ajaxtarget'))
        jQuery(link.attr('ajaxtarget')).html(data);
    });
    return false;
  }).attr("rel", "nofollow");
 
  jQuery('a.get, a.post, a.put, a.delete').removeAttr('onclick');
});


