function equalHeight(container) {
  var maxheight = 0;
  container.each(function() {
    var height = $(this).height();
    if(height > maxheight) {
      maxheight = height;
    }
  });
  //container.height(maxheight);

  container.css({height: maxheight})
}

function replaceURLWithHTMLLinks(text) {

return text.replace( /(http:\/\/[^\s]{5,})/g, "<a href=\"$1\" >$1</a>")
}

$(document).ready(function(){

    equalHeight($('.box_5_col')) 
	equalHeight($('.box_5_col_clean')) 
	
	$("a[rel='tourshots']").colorbox({transition:"fade"});
	
	$('.screenshotTooltipContainer').mouseover(function() {
			$(this).parent().delay(100).fadeOut(50); 
	});
	
	$('.mapMark').hover(
		function() {
			this.tip = this.title;
			this.title = "";
			
			this.tip_id = 	this.tip.split("_")[0]

			if (this.tip.split("_")[1] == "t")
			  this.yPos =  -$('#tip'+this.tip_id).height();
			else
			  this.yPos =  22;
		
			$('#tip'+this.tip_id).css({left: -100, top: this.yPos})
			$('#tip'+this.tip_id).fadeIn(200);
		},
		function() {
			$('.screenshotTooltip').fadeOut(50); 
			
			this.title = this.tip;
		}
	);
	
	$('.price-info').hover(
		function() {
			this.tip = this.title;
			this.title = "";
			
			$("#pricing-container").append('<div class="pricing_toolip"><div class="pricing_tooltip_arrow"><img src="/images/pricing/arrow-tooltip.png" width="9" height="14" /></div><div class="pricing_tooltip_info">'+this.tip+'</div></div>'); 
			cH = ($("#pricing-container").find('.pricing_tooltip_info').height()/2)+5; 
		
			$("#pricing-container").find('.pricing_toolip').css({left: $(this).offset().left+10+$(this).width(), top: $(this).offset().top-cH})
			$("#pricing-container").find('.pricing_toolip').fadeOut(0);
			$("#pricing-container").find('.pricing_tooltip_arrow').css({top: cH})
			$("#pricing-container").find('.pricing_toolip').fadeIn(200);
		},
		function() {
			$("#pricing-container").find('.pricing_toolip').remove(); 
			this.title = this.tip;
		}
	);	
	
	$(".colorbox_iframe").colorbox({width:"50%", height:"70%", iframe:true});
	$(".colorbox_video_convert").colorbox({width:"650", height: "420", iframe:true});
	
	if ($("#page_home").length > 0) {
		
		$.getJSON("http://twitter.com/status/user_timeline/hotgloo.json?count=3&callback=?", { } ,
		   function(data) { 
	
			for (i=0 ; i<data.length ; i++) {
				
				var tweet_text = replaceURLWithHTMLLinks(data[i].text); 
				$('#tweets').append("<div class='home-tweetbox' style='padding: 10px 0 0 0'><p><a href='http://twitter.com/#!/"+data[i].user.name+"/statuses/"+data[i].id_str+"'>"+data[i].user.name+":</a> "+tweet_text+"</p></div><div class='clear'> </div>"); 
			}
		}); 
		
		$("#btn_subscribe").click(function () {
			if (!validateMail($('#email').val())) {
				alert("Please enter a valid email address")
			} else {
				$("#home-newsletter").hide();
				$("#home-newsletter-thanks").fadeIn();
				
				$.post("/newsletter", { email: $('#email').val(), _method: "put", authenticity_token: $('[name=authenticity_token]').val() } ,
				   function(data) {
								
				   });				
				
			}
		});
	}	
	
	function loockup () 
	{
		$("#error_password").find(".signup_error_info").remove();
		
		if (!validateMail($('#email').val())) {
		  $("#error_password").append("<div class=\"signup_error_info\"  ><div style=\"left: 97px;\"><img src=\"/images/signup/error.png\" /></div><div>required</div>");
		}
		else {
			$("#lockup_start").hide(); 
			
			$("#lookup_headline").html("Please wait...");
			$("#result").show(); 
			$("#result .loader").show(); 

			$("#result_list").remove(); 
			$("#result_not").remove();			
			
			$.post("/lookup_subdomain", { authenticity_token: $('[name=authenticity_token]').val(),  email: $("#email").val() } ,
			   function(data) {
			      var accounts = eval('(' + data + ')');	
				
				  $("#result .loader").hide(); 	
			 	
			      var domain = location.host.split(".");
			
				  if (accounts.list.length > 0) {
					    $("#lookup_headline").html("This email address is connected to more than one account. Please choose the account you want to sign in...");
						$("#result").append("<div id=\"result_list\"><br /></div>")

						for (i=0 ; i<accounts.list.length ; i++) {
						  $("#result_list").append("<div class=\"btn_content_gray\"><a href=\"http://"+accounts.list[i]+"."+domain[1]+"."+domain[2]+"/signin\">"+accounts.list[i]+"</a></div>"); 	
						}					
				
					
					if (accounts.list.length == 1) {
						$("#lookup_headline").html("Redirecting...");
						window.location = "http://"+accounts.list[0]+"."+domain[1]+"."+domain[2]+"/signin";
					}					

				  }
				  else {
					 $("#lookup_headline").text("We're sorry but we can't find any account connected to this email address.");
				     $("#result").append("<div id=\"result_list\" ><br />Don't have a HotGloo account? <a href=\"/signup\">Sign up today.</a></div>"); 
				  } 
			   });			
		}
	}
	
	if ($("#lookup").length > 0)
    {
		$('#email').keypress(function(e){
		      if(e.which == 13) {
		       	loockup () 
				e.preventDefault();
		      }
		});
	
	  $("#btn_lookup").click(function () {
		loockup ();
	  }); 
	}

	if ($('#edit_project').length > 0) {
		$('#project_content_add_people').hide();
		$('#project_content_add_users').hide();
		$('#project_content_add_loader').hide();
		$('#project_content_add_split').hide();
		$('#project_content_save_loader').hide();
		
		$('#project_btn_add_people').click(function () {
			$(this).hide();	
			$('#project_content_add_people').fadeIn();
			$('#project_content_add_split').show();
			loadUserInGroup(0, "#group_user", $('[name=authenticity_token]').val());
		});
		
		$('#group_name').change(function (data) {
			loadUserInGroup($('#group_name').val(), "#group_user", $('[name=authenticity_token]').val());
		});	
		
		$('#btn_add_user').click(function () {
			var role = 3
			
			if ($("#group_role_1").attr("checked"))
				role = 2; 
				
			addUserToProject($('#group_project').val(), $('#group_user').val(), role, $('[name=authenticity_token]').val());
		});		
		
		$('#user_table .col4 a').live('click', function (event) {
		  	var target = event.currentTarget;
			removeUserFromProject($('#group_project').val(), $(target).prev().val(), $('[name=authenticity_token]').val())
			$(target).parent().parent().remove()
		});	
	}
	
	$('#btn_preview_generate').click(function () {	
		$('#preview_btns').hide();
		$('#preview_loader').show();
		
		$.post("/projects/update_viewlink", { id: $('#group_project').val(), create: true, authenticity_token: $('[name=authenticity_token]').val() } ,
		   function(data) {
			  var d = eval('(' + data + ')');
			  $('#link_preview').val(d.link)	
			  $('#preview_btns').fadeIn();
			  $('#preview_loader').hide();					
		   });
	});
	
	$('#btn_preview_drop').click(function () {		
		$('#preview_btns').hide();
		$('#preview_loader').show();
					
		$.post("/projects/update_viewlink", { id: $('#group_project').val(), authenticity_token: $('[name=authenticity_token]').val() } ,
		   function(data) {
			  var d = eval('(' + data + ')');
			  $('#link_preview').val(d.link)	
			  $('#preview_btns').fadeIn();
			  $('#preview_loader').hide();					
		   });
	});
	
	
	
	if ($('#page_groups').length > 0) {
		$('#add_group').hide();
		$('#update_group').hide();
		
		$('#group_list').change(function (data) {
			$('#add_group').hide();	
			var groupInfo = $('#group_list').val().split("[;]");
			if (groupInfo[0].length > 0)
			{
				$('#group_id').val(groupInfo[0]);
				$('#group_update').val(groupInfo[1]);
				$('#update_group').fadeIn();
			}
		});	
		
		$('#btn_add_group').click(function (data) {
			$('#add_group').fadeIn();
			$('#update_group').hide();
		});
		
		$('#btn_update').click(function (data) {
			removeErrorDiv("#error_update_name");

			if ($('#group_update').val().length < 2) {
				appendErrorDiv("#error_update_name", "required"); 
			}
			else {
				$('#update_group').hide();
				$('#group_loader').show();
				$.post("/group_update", { group_type: $('#group_type').val(), group_id: $('#group_id').val(), name: $('#group_update').val(), authenticity_token: $('[name=authenticity_token]').val() } ,
				   function(data) {
					  var d = eval('(' + data + ')');
					  $('#update_group').show();
					  $('#group_loader').hide();	
					  setGroups(d.list, $('#group_id').val());	
					  groupStatusInfo ("Group updated") 						
				   });			
			}
		});		
		
		$('#btn_delete').click(function (data) {
			$('#update_group').hide();
			$('#group_loader').show();			
			$.post("/group_delete", { group_type: $('#group_type').val(), group_id: $('#group_id').val(), authenticity_token: $('[name=authenticity_token]').val() } ,
			   function(data) {
				  var d = eval('(' + data + ')');
				  $('#group_loader').hide();	
				  setGroups(d.list, $('#group_id').val());	
				  groupStatusInfo ("Group deleted") 				
			   });		
		});		
		
		$('#btn_add').click(function (data) {

			removeErrorDiv("#error_new_name");

			if ($('#group_new').val().length < 2 ) {
				appendErrorDiv("#error_new_name", "required"); 
			}
			else {
				$('#add_group').hide();
				$('#group_loader').show();	
				$.post("/group_add", { group_type: $('#group_type').val(), name: $('#group_new').val(), authenticity_token: $('[name=authenticity_token]').val() } ,
				   function(data) {
					  var d = eval('(' + data + ')');
					  $('#group_loader').hide();	
					  setGroups(d.list, $('#group_id').val());	
					  groupStatusInfo ("Group added") 		
					  $('#group_new').val("");
				   });				
			}				
		});		
			
	}	

	if ($('#page_dupliate_project').length > 0) {	

		$.get("/projects/"+$('#project_id').val()+"/duplicate_project_action", { } ,
		   function(data) {
			  var d = eval('(' + data + ')');
			  
			  $('#ready').fadeIn();
			  $('#wait').hide();
		   });
	}
	
	if ($('#page_settings').length > 0) {	
		$('.notifi_cbox').click(function () { 
			
			$(this).hide(); 
			$(this).parent().find(".notifi_loader").show();
			$(this).parent().parent().find(".notifi_saved").hide();
			
			var ref = this; 
			
			$.post("/settings/update_notification", { value: $(this).attr('checked'), project: $(this).val(), authenticity_token: $('[name=authenticity_token]').val() } ,
			   function(data) {
				$(ref).show(); 
				$(ref).parent().find(".notifi_loader").hide();	
				$(ref).parent().parent().find(".notifi_saved").show();			  
			   });			
		})	
	}	
	
	if ($('#page_projects').length > 0) {		

     $('.project-row').hover(
		function() {
			$(this).find('.handle').css({"visibility":"visible"});
		},
		function() {
			$(this).find('.handle').css({"visibility":"hidden"});
		});
		
	 $('.project-list').sortable(
	        {
	          axis: 'y', 
	          dropOnEmpty:false, 
	          handle: '.handle', 
	          cursor: 'crosshair',
	          items: 'li',
	          opacity: 0.4,
	          scroll: true,
	          update: function(){

	            $.ajax({
	                type: 'post', 
	                data: $(this).sortable('serialize') + '&authenticity_token=' + encodeURIComponent($('[name=authenticity_token]').val()), 
	                dataType: 'script', 
	                complete: function(request){
	                  
	                  },
	                url: '/prioritize_projects'})
	            }
	          })	
	}
	
	
});

function removeUserFromProject (project, user, authenticity_token) {
	$.post("/remove_user_from_project", { project: project, user: user, authenticity_token: authenticity_token } ,
	   function(data) {
		   var d = eval('(' + data + ')');
	   });	
}

function addUserToProject (project, user, role, authenticity_token) {
	$('#btn_add_user').hide();
	$('#project_content_save_loader').show();
	$.post("/add_user_to_project", { project: project, user: user, role: role, authenticity_token: authenticity_token } ,
	   function(data) {
		   var d = eval('(' + data + ')');
			
		   $('#project_content_save_loader').hide();	
		   $('#btn_add_user').fadeIn(); 
		   
		   if (d.status) {
			  
			 if (d.role == 2)
			 {
				c = "col1 editor"
				role = "EDITOR"
			 }
			 else  {
			    c = "col1"
				role = "REVIEWER"			
			 }
			
			 $("#user_table").append("<div class='row'><div class='"+c+"'>"+role+"</div><div class='col2'>"+d.group+"</div><div class='col3'>"+d.name+"</div><div class='col4'><input type='hidden' value='"+d.id+"' /><a class='magenta btn_rounded'>DROP</a></div></div>"); 
		}	 
		
	   });	
}

function loadUserInGroup (group, dropdown, authenticity_token) {
	$('#project_content_add_users').hide();
	$('#project_content_add_loader').show();
	
	
	$.post("/get_users_by_group", { group: group, authenticity_token: authenticity_token } ,
	   function(data) {
		   var d = eval('(' + data + ')');
			 
		   if (d.list.length > 0) {
		   	var opt = '';

			for (i=0 ; i<d.list.length; i++) {	
				opt += '<option value="'+d.list[i][0]+'">'+d.list[i][1]+'</option>';
			}		
			
			$('#group_user').html(opt);
			$('#project_content_add_users').fadeIn();
			$('#project_content_add_loader').hide();
		   }	
		
	   });
}

function setGroups (list, id) {
   	var opt = '';
    
    opt += '<option value=""></option>';

	for (i=0 ; i<list.length; i++) {	
		var d = list[i][1].split("[;]");
		var s = ""
		 
		if (d[0] == id)
	      s = "selected"
		
		opt += '<option value="'+list[i][1]+'" '+s+'>'+list[i][0]+'</option>';
	}		
	
	$('#group_list').html(opt);	
}

function groupStatusInfo (message) {
  $('#status').append("<div class=\"success\" style=\"width: 90%\">"+message+"</div>")	
  $('#status').find(".success").delay(2000).fadeOut();	
}

function appendErrorDiv (elem, str) {
	var txt = "required";
	
	if (str.length > 0)
		txt = str; 
		
	$(elem).append("<div class=\"signup_error_info\" ><div><img src=\"/images/signup/error.png\" /></div><div>"+txt+"</div>");
}

function removeErrorDiv (elem) {
	$(elem).find(".signup_error_info").remove();
}

function validateMail (email) {
   var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

	if(email == '')
		return false;
	if(!emailReg.test(email)) 
		return false
		
	return true; 
}

 
function launchColorBox(id, title)
{
	$.colorbox({href:"http://player.vimeo.com/video/"+id+"?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1&amp;loop=1",width:"550", height:"396",iframe:true,title: title});
}



