var platform = /(Win|Mac|Linux|iPhone)/.exec(navigator.platform)[0];
if (jQuery.browser.mozilla){
	var agent_version = parseFloat(/Firefox\/(.+)/.exec(navigator.userAgent)[1]);
}else{
	var agent_version = parseFloat(jQuery.browser.version);	
}

function ie6(){
	if(jQuery.browser.msie && (jQuery.browser.version <= 6)){return true;};
	return false;	
}

$(document).ready(function(){
	imgLoader = new Image(); 
	imgLoader.src = "/images/progress_bar.gif";
	
	thickbox_init('a.thickbox'); 
	$('.glossary').glossary();
	
	$("input[type='hidden']").css('border', 'none');		
	
	if(jQuery.browser.msie){
		$("input[type$='checkbox']").css('border', 'none');
		$("input[type$='radio']").css('border', 'none');		
	}
		
	$("div.fancy_box").each(function(){
		var parent_width = $(this).parent().width();
		var width = $(this).width();
		if (width > parent_width){width = parent_width;}//safari fix		
		var font_size = parseInt($(this).css('font-size'));
		var ems = width / font_size;		
		$(this).css('width', 'auto');
		$(this).wrap("<div class='dialog' style='width:"+ems+"em'><div class='bd'><div class='c'><div class='s'></div></div></div></div>");
	});
	$('div.dialog').prepend("<div class='hd'><div class='c'></div></div>").append("<div class='ft'><div class='c'></div></div>");	
});
 
// START - RESTFUL AJAX  
var AJAX_ACTIONS = ['delete', 'put', 'post', 'get'];
var AJAX_ERROR_MSG = "<div id='error'>The request can not be completed at this time.</div>";

jQuery.ajaxSetup({ // NOTE: if you use any of the following callbacks in an AJAX call it will OVERRIDE these
  	beforeSend: function(xhr) {
		//xhr.setRequestHeader("Accept", "text/javascript");
		if(tb_is_open()){ 
			$('#TB_load').show(); 
		};
	},
	timeout: 10000,
	error: function(){ 
		if(tb_is_open()){ $("#TB_status").html(AJAX_ERROR_MSG); } else { $("#flash_container").html(AJAX_ERROR_MSG); }
	},
	complete: function(){
		if(tb_is_open()){ 
			$('#TB_load').hide(); 
			thickbox_init("#TB_ajaxContent a.thickbox"); 
			$("#TB_window").css({display:"block"}); 
		}
	}
})

function tb_is_open(){
		if($('#TB_window')[0] != null){	return true; };
		return false;
}

function restful_ajax(method, path){
	var target_element = $('#TB_window');	
	var width = $('#TB_ajaxContent').width();
	var height = $('#TB_ajaxContent').height();
	var caption = $('#TB_ajaxWindowTitle').text();
	
	if(jQuery.inArray(method.toLowerCase(), AJAX_ACTIONS) < 0){ return false; }	
	if(jQuery.browser.msie && (jQuery.browser.version <= 8)){// TODO: check to see if ie 8 supports delete and put??
		path = path + "?_method="+method;
		method = 'post';
	};
	if(check_session()){
		$.ajax({
			url: path,
			type: method,
			contentType: 'text/javascript',
		 	dataType: 'html',	
			success: function(html){
				target_element.html(html);
				thickbox_resize(width, height);
				$('#TB_ajaxWindowTitle').text(caption);
			}
		});
	}
	return false;
}

function ajaxify_message_forms(messages_array){

	$.each(messages_array, function(i, n){
		$('#new_message_form_' + n).submit(function(){
			var width = $('#TB_ajaxContent').width();
			var height = $('#TB_ajaxContent').height();
			var caption = $('#TB_ajaxWindowTitle').text();
			$('#TB_load').show();
			
			if(check_session()){ 
				$('#TB_window').hide();			
				$('#new_message_form_' + n).ajaxSubmit({
					success: function(html){
						$('#TB_load').hide(); 							
						$('#TB_window').html(html);	
						thickbox_resize(width, height);	
						$('#TB_ajaxWindowTitle').text(caption);						
						$('#TB_window').show();	
					}
				});	
			}
			return false;
		});
	});
}


function thickbox_form_submit(form_id, options){
	if(tb_is_open())//Verify thickbox is accessible
	{
		_form = $("#"+form_id);
		_form.submit(function(){
		  if(check_session()){
			$(this).ajaxSubmit(options);
			hide_buttons(form_id);
		  };
		  return false;
		});
	}
}

//END - RESTFUL AJAX

// Thickbox start

function thickbox_resize(width, height){
	$("#TB_title_tr").width((width+3));
	$("#TB_ajaxWindowTitle").width((width-61));
	$("#TB_ajaxContent").css({'width': width+'px', 'height': height+'px'});		
	$("#TB_footer_br").width((width+3));
}

function check_session(){
	var valid_session = false;
	$.ajax({
		async: false,
	    url: '/check_session',
	    dataType: 'text',
		success: function(data){
			if(data == "ok") {
				valid_session = true;
			}else{
				window.location = "/";
			}
		}
	});
	return valid_session;
}

function thickbox_init(domChunk){
	$(domChunk).click(function(){
		$("#flash_container").html("&nbsp;");//remove any flash messages before loading a lightbox		
		var caption = this.title || this.name || null;
		var url = this.href || this.alt;
		thickbox_flex_load(caption, url);	
		this.blur();
		return false;
	});
}

function thickbox_flex_load(caption, url){
	if (check_session()){ thickbox_show(caption, url); }
}

function thickbox_show(caption, url) {
	try {
		if (ie6()) {		
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(thickbox_remove);
			}
		}else{//all other browsers
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(thickbox_remove);
			}
		}

		if(thickbox_detectMacXFF()){
			if(jQuery.browser.mozilla && (agent_version < 3) && (platform == 'Mac')){
				$('#container').css('visibility','hidden');
			}
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{			
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity			
		}

		if($("#TB_load")[0] == null){ $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>"); }//add loader to the page
		$('#TB_load').show();//show loader

		var baseURL;
	    if(url.indexOf("?")!==-1){ //if there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	    }else{ 
	   		baseURL = url;
	    }
		
		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = thickbox_parseQuery( queryString );
		if(caption===null){caption="";}		
		
		window_height = get_page_size()[1];		
		tb_height_default = window_height - 80;
		if(tb_height_default < 540){ tb_height_default = 540; }
		if(tb_height_default > 600){ tb_height_default = 600; }		
		
		caption = params['title_override'] || caption;		
		TB_WIDTH = (params['width']*1) + 30 || 970; 
		TB_HEIGHT = (params['height']*1) + 45 || tb_height_default;		

		ajaxContentW = TB_WIDTH - 30;
		ajaxContentH = TB_HEIGHT - 45;
		
		if($("#TB_window").css("display") != "block"){// new thickbox window	
			if(params['modal'] != "true"){
				$("#TB_window").html("");//clear any existing content			
			}else{//modal
				$("#TB_overlay").unbind();
				$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
			}
		}else{//this means the window is already up, we are just loading new content via ajax for thick box calls from with-in a thickbox
			$('#TB_window').hide();
			//$("#TB_ajaxContent")[0].scrollTop = 0;				
		}
		
		$.ajax({
			url: url,
			dataType: 'html',
			success: function(html){
				$("#TB_load").hide();
				$("#TB_window").html(html);			
				if(caption){
					if($('#preferences_notice')[0] == null){
						$('#TB_ajaxWindowTitle').text(caption);
					}
				};
				thickbox_resize(ajaxContentW, ajaxContentH);				
				thickbox_position();				
				$('#TB_window').show();				
				//if(ie6()){ie6_button_hover('TB_close');};			
				$("#TB_close_button").click(thickbox_remove);					
			}
		});
		
		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					thickbox_remove();
				}	
			};
		}

	} catch(e) {
		//nothing here
	}
}

function thickbox_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	if(jQuery.browser.mozilla && (agent_version < 3) && (platform == 'Mac')){ //Firefox2 OSX 			
		$('#TB_window, #TB_overlay, #TB_HideSelect').unbind().remove();
		$('#container').css('visibility','visible');
	}else{
		$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});		
	}
	$("#TB_load").remove();
	if (ie6()) {
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function thickbox_parseQuery ( query ) {
   var Params = {};
   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 thickbox_position() {
	$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(ie6())) { 
		$("#TB_window").css({marginTop: '-' + (parseInt((TB_HEIGHT / 2),10)+20) + 'px'});
	}
}

function get_page_size() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
	arrayPageSize = [myWidth, myHeight];
	return arrayPageSize;
}

function thickbox_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
// Thickbox End

function ie_image_vertical_center(img_dom_path, max_height, offset, ie6_only){
	var ie_version = 7;
	if(ie6_only){ ie_version = 6; }
	if(jQuery.browser.msie && (jQuery.browser.version <= ie_version)){
		var images = $(img_dom_path);		
		images.each(function(){
			var height = $(this).height()+4;
			var margin_top = parseInt((max_height - ($(this).height()))/2);
			$(this).css('margin-top', margin_top + offset);
		});			
	}
}

function flex_resize(){	
	if(jQuery.browser.msie && (agent_version == 7)){ $('#active_container').hide(); }
	var head_foot_offset = 138;
	var psize_array = get_page_size();
	var flex_height = psize_array[1] - head_foot_offset;
	if(flex_height < 375){
		flex_height = 375;
	}
	$('#content').height(flex_height);
	$('#familyTreeBuilder').height(flex_height);	
	if(jQuery.browser.msie && (agent_version == 7)){ $('#active_container').show(); }
}

function redirect_for_dna_profile_nav() {
	$(document).ready(function (){
		$("#ydna_radio, #mtdna_radio").click(function(){
	   		$("#ydna_radio").attr('disabled', 'disabled');
	   		$("#mtdna_radio").attr('disabled', 'disabled');
			window.location = $(this)[0].value; 
		});
	});
}

function change_title(title_position){
	titles = ["Preferences &amp; Privacy", "Notification Settings"];
	var new_title = "My "+titles[title_position];
	$('#preferences_title').html(new_title);
}
function preferences_setup() {
	$(document).ready(function(){
	  $('#preferences_menu_wrap').tabs(2);
		$('#preferences_menu_wrap').bind('tabsselect', function(event, ui) {
			index = ui.index;
			change_title(index);
		});
      change_title(0);
      $('#notification_defaults').click(function(){checkCheckboxes('notification');});
      $('#privacy_defaults').click(function(){privacy_defaults();});
       if(jQuery.browser.safari){
       	  $('.notifications_offset .preferences_buttons').css('margin-top', '188px');
       }
       if(jQuery.browser.msie){
			$('.notifications_col1').css('line-height', '1');	
			$('.notifications_col1 div').css('line-height', '1');
			$('.notifications_offset .preferences_buttons').css('margin-top', '158px');
       }
	//bind the forms
	$('form#privacy_preferences_form').ajaxForm({ success: function() {show_buttons("privacy");}});
	$('form#notification_preferences_form').ajaxForm({ success: function() {show_buttons("notification");} });	
	//submit forms via ajax
	 $('form#privacy_preferences_form').submit(function() {
		hide_buttons('privacy');
 		 $(this).ajaxSubmit(); 
 		 $('form#notification_preferences_form').ajaxSubmit(); 
 		 return false;
      });         
      $('form#notification_preferences_form').submit(function() {
		hide_buttons('notification')
 		 $(this).ajaxSubmit(); 
 		 $('form#privacy_preferences_form').ajaxSubmit(); 
 		 return false;
       });
  });
}
function show_buttons(type) {
	$('#'+type+'_progress_bar').hide();
	$('#'+type+'_submit').show();
	$('#'+type+'_cancel').show();
	$('#'+type+'_defaults').show();
	fade_element_in_and_out("#preferences_notice");
}
function checkCheckboxes(form_id){
	$("#"+form_id+"_preferences_form").find("input[type$='checkbox']").each(function(){
    	this.checked = true;
    });
}
function privacy_defaults(){
	// todo: dry this up--we do it in the view and model--refactor this to use the mvc pattern
	$("#privacy_preferences_form").find("input[type$='checkbox']").each(function(){
    	this.checked = false;
    });
	defaults = ['family_permissions_view_birthdate', 'friends_permissions_view_birthdate', 'dna_permissions_view_birthdate',
				'family_permissions_view_birthplace', 'dna_permissions_view_birthplace', 'friends_permissions_view_birthplace',
				'family_permissions_view_posts_comments', 'friends_permissions_view_posts_comments', 'dna_permissions_view_posts_comments',
				'family_permissions_view_dna', 'dna_permissions_view_dna', 'public_permissions_view_name_dna_matches',
				'family_permissions_view_location','friends_permissions_view_location','dna_permissions_view_location',
				'family_permissions_view_description','friends_permissions_view_description','dna_permissions_view_description',
				'family_permissions_view_media','friends_permissions_view_media','dna_permissions_view_media'];
	$.each(defaults, function(i, n){
    	$("#"+n).attr("checked", "checked");
    });	
}
function fade_element_in_and_out(selector, msg_class){
	if(msg_class != null){ $(selector).addClass(msg_class) };
	$(selector).fadeTo(10, 0, function() {$(this).removeClass("hidden")}).fadeTo("slow", 1).fadeTo(3000, 1).fadeTo("slow", 0, function() {$(this).addClass("hidden")	});
}

function hide_buttons(type) {
	$('#TB_load').remove();
	$('#'+type+'_submit').hide();
	$('#'+type+'_defaults').hide();
	$('#'+type+'_cancel').hide();
	$('#'+type+'_progress_bar').show();
}

function ie6_rollover(id){ // using /javascripts/rollover.htc file now for ie6
	var button = $("#"+id+"_button");
	button.hover(function() {
	  $(this).addClass('hover');
	}, function() {
	  $(this).removeClass('hover');
	});
	button.focus(function(){$(this).addClass('hover');});
	button.blur(function(){$(this).removeClass('hover');});
}

function fade_flash(){
	setTimeout(function() { $('#notice').fadeTo(500, .1).slideUp(500); }, 10000);
	setTimeout(function() { $('#error').fadeTo(500, .1).slideUp(500); }, 10000);
}

function prepend_string(str){
  if(str.indexOf("#") == -1){
    return "#"+str;
  }
  return str;
}
function check_select_other(select_id){
  select_id = prepend_string(select_id)
	var selection = $(select_id).value;
	if(selection == "Other"){
		$(select_id + "_wrap").hide();
		$(select_id + "_other_wrap").show();
		$(select_id + "_other").focus();
	}
}
function show_select(select_id){
  select_id = prepend_string(select_id)
	$(select_id+"_wrap").show();
	$(select_id+"_other_wrap").hide();	
}
function other_check(select_id){
  select_id = prepend_string(select_id)
	var value = $(select_id + "_other").value;
	if(value.blank()){
		show_select(select_id);
	}
}
function check_details(){
	var details = $('#feedback_details');	
	if($.trim(details.val()) == ""){
		details.css("border","1px solid red");
		details.focus();
		$('#error').show();
		return false;
	}
	return true;
}
function clear_error(){
	var details = $('#feedback_details');
	if($.trim(details.val()) != ""){
		$('#error').hide();
		details.css("border", "1px solid #ccc");
	}
}
function swapImg(dom_id, new_img_path){
    dom_id = prepend_string(dom_id)
	$(dom_id).attr('src', new_img_path);
}
function toggle_blind_focus(toggle_id, focus_id) {
	toggle_id = prepend_string(toggle_id)
	focus_id = prepend_string(focus_id)
	$(toggle_id).slideToggle(400);
	$(toggle_id).queue(function() {
	  if ($(toggle_id).is(':visible')) {$(focus_id).focus();}
	  $(this).dequeue();
  	});
}
function show_children(root){
	$("div.root_"+root).show();
}
function hide_children(root){
	$("div.root_"+root).hide();
}
function toggle_children(root){
  $("div.root_"+root).toggle();
}

var Photo = {
  upload: function(){
	$('#loading').show();
	$('#loading').css("color","#666")
	$('#loading').text('Uploading...')
    $('#photo_upload').submit();
  },  
  finish: function(url) {
    window.location.href = url;
  },
  error: function(msg){
	$('#loading').css("color","red")	
	$('#loading').text(msg);
  }  
}

function hover_for_collection(selector, class_name) {
	$("#"+selector).each(function(){
		$(this).hover(function(){
			$(this).addClass(class_name);},
			function(){
				$(this).removeClass(class_name);
		})
	});
}

function load_jcarousel(options){
	var defaults={};
    $("#jcarousel_container").jcarousel($.extend({}, options, defaults));
}

function load_asset (path, selected_link_id, film_strip){
	var load_img = new Image();
	load_img.src = '/images/ajax-loader.gif';
	var loading_text="<img id='asset_loading' src='/images/ajax-loader.gif' alt='Ajax Loading Image'/>";
	$.ajax({
	    url: path,
	    dataType: 'text',
		beforeSend: function(){
			$("#current_file_container").html(loading_text); 
			if (film_strip)
			{
				$("#jcarousel_container li.jcarousel-item-current:first").removeClass("jcarousel-item-current");
				$("#"+selected_link_id+"_item").addClass("jcarousel-item-current");
			}
			else
			{
				$("#asset_icons a img.asset_icon_current:first").removeClass("asset_icon_current");	
				$("#"+selected_link_id+"_thumbnail").addClass("asset_icon_current");
			}
		},
		error: function(){$("#error").html("<div id='error'>You tried to perform a command that could not be carried out at this time.</div>");},
		success: function(data){
			$("#asset_body").html(data);
			$('#current_file_container img').fadeIn(2000);
		}
	});	
}

function highlight_edit (input_id) {
	reset_color = $("#store_wrapper_color_to_reset").css("background-color");
	$("#"+input_id).animate({ backgroundColor: '#FFFF66' }, 1000).animate({ backgroundColor: reset_color}, 500);
	$("#"+input_id+"_wrapper").css("background-color", reset_color);
	
}

function asset_editables (save_path) {	
	$(".edit").editable(save_path,
	{
		indicator : "Saving...<img src='/images/ajax_mini_loader_gray.gif' alt='AJAX indicator' />",
		tooltip   : 'Click to edit...',
		cssclass  : 'jEditable',
		cancel    : 'Cancel',
		submit    : 'Save',
		width	  : '85%',
		height	  : '1.4em',
		loadtype  : 'POST',
		highlight : true,
		highlight_color : "#E5E5E5",
		callback  : function(){ highlight_edit($(this).attr("id")) }
    });

	$(".edit_area").editable(save_path, 
	{ 
		type      : 'textarea',
		cancel    : 'Cancel',
		submit    : 'Save',
		width	  : '90%',
		rows	  :	'4',
		indicator : "Saving...<img src='/images/ajax_mini_loader_gray.gif' alt='AJAX indicator' />",
		tooltip   : 'Click to edit...',
		cssclass  : 'jEditable',
		loadtype  : 'POST',
		highlight : true,
		highlight_color : "#E5E5E5",
		callback  : function(){ highlight_edit($(this).attr("id")) }
	});
}

function contact_highlight(id){
	$('#contact_'+id).addClass('contact_highlighted')
}

function show_password_when_updating_email() {
	$('#verify_pswd').show();
	$('#verify_pswd').focus(); 
	$('#account_password').css("borderColor","#f00");
}

function strip_simple_formatting(html){
	return $.trim(html).replace(/<(p|\/p|br)>/gi, '\n');
}
function add_html_breaks(html){
	return $.trim(html).replace(/\n/g, '<br>');	
} 

function load_haplogroup_content(group_name, target_element, type) {
	var mtdna_path = "/dna/education/mtDNA/descriptions/";
	var ydna_path = "/dna/education/Y_DNA/descriptions/";
	
    switch (type) {
        case "mtdna":
            url = mtdna_path + group_name + ".html";
            break;
        case "ydna":
            url = ydna_path + group_name + ".html";
            break;
        default:
            url = mtdna_path + group_name + ".html";
    }

	$.ajax({
		url: url,
		dataType: 'html',
		success: function(html){
			$('#'+target_element).html(html);						
		},
		complete: function(html){
			$('.glossary').unbind("click");
			$('.glossary').glossary();
		}
	});			
}