var debug;

function report_error(message) {
  $('#error_msg p').html(message);
  $('#error_msg').show('slow', function(){
    window.setTimeout("$('#error_msg').hide('slow');", 5000);
  });
}
function _tabs_init(){
  // Tabs
  $('div.tabs ul.tab_navigation a').click(function () {
    $('div.tabs > div').hide().filter(this.hash).show();
    
    $('div.tabs ul.tab_navigation a').removeClass('selected');
    $(this).addClass('selected');
    
    return false;
  });
  
  selected = $.query.get('t');
  selected_tab = $('div.tabs ul.tab_navigation a[href=#'+selected+']');
  if (selected_tab.length > 0) {
    selected_tab.click();
  } else {
    $('div.tabs ul.tab_navigation a').filter(':first').click();
  }
}
// Set timezone cookie. Returns offset in minutes.
// Seems to be negated (was returning 5 for me in EST) so negate again to fix.
document.cookie = "timezone=" + escape(new Date().getTimezoneOffset() * -1) + ";path=/";
function _dashboard_init() {
  //Help Text Bubbles
  
  $("input,textarea").focus(function () {
    try {
      bubble_id = $('#'+this.id).parent()[0].id;
      if (bubble_id) { $('.'+bubble_id).fadeIn(150); }
    } catch(e) {
    }
  })
  
  $("input,textarea").blur(function () {
    try {
      bubble_id = $('#'+this.id).parent()[0].id;
      if (bubble_id) { $('.'+bubble_id).fadeOut(150); }
    } catch(e) {
    }
  })
  
  $('.superflirts-footer .picks p.last a').click(function(){
    try {
      $('#super-flirts-area').slideUp(1000);
      $.ajax({
        type: "GET",
        url: '/superflirts/skip',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          // report_error(XMLHttpRequest.responseText);
        },
        beforeSend: function(){
        },
        success: function(json){
        }
      });
    } catch(e) {
    }
    return false; 
  })
  
}  
function _query_profiler_init() {
  // Query dashboard
  $("#query_profiler div:first").click(function(){
    $("#queries").slideToggle('hide');
  });
  $("#query_profiler a.explain").click(function(e){
    query = $(this).attr("query");
    id = $(this).attr("i");

    $.get("/debug", {"query": query}, function(data, status){
      explain = "<tr><td colspan='5'>"+data+"</td></tr>";
      $("#query_profiler_"+id).after(explain);
    });
  });
  $("#query_profiler a.stack").click(function(e){
    id = $(this).attr("i");
    $("#query_profiler_stack_"+id).css('display','table-row');
  });
}
function _resizable_text_area_init() {
  // Resizable Text Areas
  $('textarea.resizable:not(.processed)').TextAreaResizer();
};
function _profile_photos_init() {
  //Profile Photo Delete
  $("a.photo_delete").livequery('click', function(e){
    e.preventDefault(); //disable the click
    element = $(this).parent();
    element.fadeTo('slow', 0.4);
    $.ajax({
      type: "DELETE",
      url: $(this).attr('href'),
      success: function(data, textStatus) {
        element.remove();
        distributePhotoChanges();
      },
      error: function(request, textStatus, errorThrown) {
        element.fadeTo('slow', 1);
        alert(request.responseText);
        // In the case of an error just remove it. They probably clicked twice
        // in succession
        //element.remove();
      }
    });
  });
  
  // Profile Photo Private/Public
  $("a.photo_lock, a.photo_unlock").livequery('click', function(e){
    e.preventDefault(); //disable the click
    badge = $(this);
    $.ajax({
      type: "POST",
      url: $(this).attr('href'),
      success: function(data, textStatus) {
        badge.toggleClass('photo_lock').toggleClass('photo_unlock');
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      }
    });
  });
  
  // Profile photo reordering
  var original_sort_order;
  $('.profile_photo_list.public, .profile_photo_list.private').sortable({
    start: function(e,ui){
      // Ugly, but it works
      $('.profile_photo_list a[rel="lightbox-profile"], .profile_photo_list a[rel="lightbox-private"]').unbind(); // removes lightbox;
    },
    stop: function(e, ui) {
      if($('.profile_photo_list.public .thumb_list').size() == 0){
        $(ui.sender).sortable('cancel');
        $(this).sortable('cancel');
        alert("You must have at least 1 public image before you can have a private image");
      } else if ($('.profile_photo_list.public .thumb_list.moderated').size() > 0){
        $(ui.sender).sortable('cancel');
        $(this).sortable('cancel');
        alert("Cannot move this photo to your public gallery. Moderators have marked this image as private");
      } else {
        public_ids  = $('.profile_photo_list.public').sortable('serialize',  {key : 'public[]' });
        private_ids = $('.profile_photo_list.private').sortable('serialize', {key : 'private[]'});
        
        $.ajax({ 
          type: "POST",
          url: "/photos/reorder",
          data: public_ids+'&'+private_ids,
          error: function(XMLHttpRequest, textStatus, errorThrown) {
            $(ui.sender).sortable('cancel');
            $(this).sortable('cancel');
          },
          success: function() {
            var lock = ui.item.children('a.photo_lock')
            if(lock.parent().parent().hasClass('public')){
              lock.fadeOut();
            } else {
              lock.fadeIn();
            }
            distributePhotoChanges();
          }
        });
        // turn lightbox back on in 50 milliseconds. if you do it without the delay, lightbox grabs the drop event
        // and treats it as a click, opening the lightbox. doing it like this, with the delay, works. hack hack hack!
        setTimeout("$('.profile_photo_list a[rel=\"lightbox-profile\"], .profile_photo_list a[rel=\"lightbox-private\"]').lightbox();", 50);
        // remove click event from image... it has been replaced with lightbox
        $('.profile_photo_list a[rel="lightbox-profile"], .profile_photo_list a[rel="lightbox-private"]').click(function(){return false;})
      }
    },
    connectWith: ['.profile_photo_list']
  })
  
  // Edit in Place
  $('.edit_area').livequery(function(){ 
    $(this).editable(function(value, settings) {
        url = "/photos/" + $(this).attr('id').split('_')[1];
        $.ajax({
          type: "PUT",
          url: url,
          data: "photo[caption]=" + value
        });
        return(value);
      }, { 
        type      : 'textarea',
        submit    : 'Save',
        cancel    : 'Cancel',
        tooltip   : 'Click to edit...',
        placeholder: 'Click to edit caption'
    });
  })
  
  $('.upload_reminder').livequery('click', function(e) {
    e.preventDefault(); //disable the click
    selected_tab = $('div.tabs ul.tab_navigation a[href=#photos]');
    if (selected_tab.length > 0) {
      selected_tab.click();
    }
  })
  
}

function photoUrlToSize(url, targetSize) {
  bits = url.split('/');
  filename = bits.pop().split('_');
  filename.shift();
  
  return bits.join('/')+'/'+targetSize+'_'+filename.join('_');
}

function distributePhotoChanges() {
  try { small_url = $('.profile_photo_list.public > div:first').find('img')[0].src; } catch(e) { small_url = ''; };

  // clear the existing thumbnails below the main profile pic
  thumbDiv   = $('#thumb_list');
  thumbDiv.html('');
  
  main_profile_img = $('#main_photo')[0];
  login_box_img    = $('#login_box').find('img')[0];
  
  if (small_url != '') {
    // remove upload reminder
    $('#mini_gallery > .upload_reminder').remove();
    
    // copy new main photo
    main_profile_img.src = photoUrlToSize(small_url, 'medium');
    login_box_img.src    = photoUrlToSize(small_url, 'mini');

    // copy first 4 photos
    fourImages = $('.profile_photo_list.public > div:lt(4)').find('img');
    fourImages.each(function(n) {
      thisSrc = fourImages[n].src;
      imgHtml = '<a class="thumb_mini" href="'+photoUrlToSize(thisSrc, 'medium')+'"><img src="'+photoUrlToSize(thisSrc, 'mini')+'"/></a>';
      thumbDiv.append(imgHtml);
    })
    
    thumbDiv.find('a:first').addClass('thumb_selected');
    thumbDiv.find('a:last').addClass('last');
  } else {
    // no images found, so insert a sillouette
    gender = $('#gender').attr('gender')
    
    if (gender == 'f') {
      gender_prefix = 'fe';
    } else {
      gender_prefix = '';
    }
    
    main_profile_img.src = '/images/medium_profile_default_'+gender_prefix+'male.png';
    login_box_img.src    = '/images/mini_profile_default_'+gender_prefix+'male.png';
    
    // insert upload reminder
    $('#mini_gallery').prepend('<a class="upload_reminder" href="">Upload a Photo</a>');
  }

  
  var count = $('.profile_photo_list .thumb_list').length;
  var disabled = false;
  for (var i in SWFUpload.instances) {
    var swfu = SWFUpload.instances[i];

    if(!disabled) disabled = count >= swfu.settings.file_upload_limit;

    swfu.setButtonDisabled(disabled);

    var stats = swfu.getStats();
    stats['successful_uploads'] = count;
    stats['files_queued'] = count;
    swfu.setStats(stats);
  }

  if(disabled){
    $("button.disallow_photo_upload").show();
  } else{
    $("button.disallow_photo_upload").hide();
  }
}
function async_google_analytics(account_id){
  var gaurl='http'+(document.location.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com/ga.js';
  var jqc=$.ajaxSettings.cache;
  $.ajaxSettings.cache=true;
  $.getScript(gaurl,function(){
    var pageTracker=_gat._getTracker(account_id);
    pageTracker._trackPageview();
  });
  $.ajaxSettings.cache=jqc;
}
// display a sexy alert message
function alert(msg){
  $('html, body').animate({scrollTop:0}, 'fast');
  $('.jqmAlertWindow:first')
    .find('div:first')
      .removeClass('jqmNoticeTitle')
      .addClass('jqmAlertTitle');
  $('#alert')
	  .find('div > div:first')      
      .removeClass('jqmAlertTitle')
      .addClass('jqmNoticeTitle');
  $('#alert')
		.jqmShow()
		.find('div.jqmAlertContent') 
			.html(msg);
}

function _site_init() {

  // move the jq modal to the top of the div for firefox 2 (ie, gecko version 1.8)
  if ($.browser.version < "1.9" && $.browser.mozilla) {
    if ($('.jqmWindow,.jqmAlert')) {
      $('body').prepend($('.jqmWindow,.jqmAlert').remove());
    }
  };
  
  function baseURL() {
    'http://'+window.location.host;
  }
  function currentLogin() {
    $('#login_box > a')[0].href.split('/').pop();
  }
  
  //jqModal Alerts
  $('#alert').jqm({overlay: 0, modal: true, trigger: 'false'});
  $('body.profile_being_screened a.screening_alert').click(function() { 
    $('html, body').animate({scrollTop:0}, 'fast');
    $('.jqmAlertWindow:first')
      .find('div:first')
        .removeClass('jqmNoticeTitle')
        .addClass('jqmAlertTitle');
    alert("Your profile has been submitted for screening.\nIn the meantime, you can instantly become approved by filling out more details about yourself!");
    return false;
  });


  //Thumbnail Info Bubbles
  $("#viewed_me .thumb_mini, #new_members .thumb_mini, #near_me_activity .thumb_small, #views .thumb_mini").hover(function() {
    $(this).children(".hoverinfo").fadeIn(100);
  }, function() {
    $(this).children(".hoverinfo").fadeOut(100);
  });
  
}
function _feedback_init() {
  // Feedback Tab
  $("#feedback a.btn_feedback").click(function(e){
		e.preventDefault(); //disable the click
    if (!$(this).hasClass('selected')) {
      $("#feedback").animate({
          left: "0px"
          }, 300 );
      $('#feedback_tab a').addClass('selected');
      $("#openCloseIdentifier").show();
    } else {
      $("#feedback").animate({
          left: "-242px"
          }, 300 );
      $('#feedback_tab a').removeClass('selected');
      $("#openCloseIdentifier").hide();
    }
  });

  // Cancellation is disabled if the .cancellation_note div exists
  if ($('.feedback_cancellation_note').length > 0) {
    var cancellation_check = function() {
      $('.feedback_cancellation_note').hide()
      $('#feedback_form #submit').show()
      $('#feedback_form textarea').show()
      $("#feedback_category option:selected").each(function () {
        if ($(this).text() == "Cancellation") {
          $('.feedback_cancellation_note').show()
          $('#feedback_form textarea').hide()
          $('#feedback_form #submit').hide()
        }
      });
    }
    cancellation_check()
    $("#feedback_category").change(cancellation_check);
  }

  function hideFeedbackForm() {
    $("#feedback").animate({ 
     left: "-242px"
		 }, 300 );
    $('#feedback_tab a').removeClass('selected');
    $("#openCloseIdentifier").hide();
  }

  $("#feedback a.btn_close").click(function(e){
	  e.preventDefault(); //disable the click
    hideFeedbackForm();
  });
  
  $('#feedback_data').ajaxForm({
    dataType: 'json',
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      // report_error(XMLHttpRequest.responseText);
    },
    success: function(json){    
      if(json.hasErrors) {
        elem = $('#feedback_form').children('p');
        elem.hide();
        elem.html(json.status_message);
        elem.slideDown();
      } else {
        $("#notification_message").html(json.status_message);
        hideFeedbackForm();
      }
    }
  });
}

function _contact_us_init() {
  // Cancellation is disabled if the .cancellation_note div exists
  if ($('.contactus_cancellation_note').length > 0) {
    var contact_cancellation_check = function() {
      $('.contactus_cancellation_note').hide()
      $('#feedback_data .submit-area').show()
      $("#contact_us_category option:selected").each(function () {
        if ($(this).text() == "Cancellation") {
          $('.contactus_cancellation_note').show()
          $('#feedback_data .submit-area').hide()
        }
      });
    }
    contact_cancellation_check()
    $("#contact_us_category").change(contact_cancellation_check);
  }
}
function _gallery_init() {
	$('#thumb_list a').live("click", function(){
	  $('#thumb_list a').removeClass('thumb_selected');
    $(this).addClass('thumb_selected');
	  var mainPath = $(this).attr('href');
	  $("#main_photo").fadeTo(200,0,function() {
      $("#main_photo").attr({src : mainPath});
    }).fadeTo(200, 1);
	  return false;
	});
}
function _gift_slider_init() {
  // Gifting Slider
  $("#gift_links").jFlow({
		slides: "#gift_container",
		controller: ".jFlowControl", // must be class, use . sign
		slideWrapper : "#jFlowSlide", // must be id, use # sign
		selectedWrapper: "jFlowSelected",  // just pure text, no sign
		width: "640px",
		height: "285px",
		duration: 400,
		prev: ".jFlowPrev", // must be class, use . sign
		next: ".jFlowNext" // must be class, use . sign
	});
}

function _gift_select_upsell_init() {
  //jqModal Alerts
  if ($('#gift_upgrade').length > 0) {
    $('#gift_upgrade').jqm();
  }

  $('.gift').click(function() { 
    $('html').animate({scrollTop:0}, 'fast');
    $('#gift_upgrade').jqmShow();
    return false;
  });
}

function _gift_select_init() {
	$('.gift').click(function(){
	  $('.gift img.icon_select').fadeOut(150);
	  selected = $(this);
    selected.children('img.icon_select').fadeIn(300, function(){
      gift_url = selected.children('img')[1].src;
      $('#selected_image img')[1].src = gift_url;

      defaults = selected.children('input[type=hidden]')[0];
      $('#gift_message textarea').attr('value', defaults.value);
      $('#gift_message_attachable_id').attr('value', defaults.id);
      
      $('#gifts').animate({opacity: 1.0}, 500).fadeOut(300, function(){
        $('#gift_message').fadeIn(200);
      });
    });
  });

  $('#gift_message a.new_gift').click(function(){
    $('#gift_message').fadeOut(300, function(){
      $('#gifts').fadeIn(300);
    });
    return false;
  });
  
  $('#new_gift_form').ajaxForm({dataType:'script'});
}
function _profiles_init() {
  $('a.btn_report').click(function () {
    $('#report').slideToggle('fast');
  });

  //Nicely format long Profile Question labels
  $('.profiles p label').each(function(){  
    var labelLength = $(this).text().length;
    if (labelLength > 30) {
      $(this).css({ lineHeight: "13px" });
    }
  });

  // Toggle Images for block/favorite
  $(".toggle_hover").livequery(function(){
    $(this).hover(function() {
      //this.src = this.src.replace('_t.p', '.p');
      //this.src = this.src.replace('.p', '_t.p');
    }, function() {
      //this.src = this.src.replace('_t.p', '.p');
    });
  });
  // Ajaxify block/favorites/photo_permissions
  $(".flags form").livequery(function() {
    $(this).ajaxForm({
      dataType: 'json',
      success: function(responseText, statusText){
        li_id = $(responseText.html)[0].id;
        li_content = $(responseText.html).html();
        $('#'+li_id).fadeTo(300,0, function() {
          if (responseText.my_favorites_count) {
            $('#my_favorites_link').html('My Favorites ('+responseText.my_favorites_count+')');
          }
          if(responseText.my_photo_permissions_count){
            $('#sidebar_private_access').html('Private Access ('+responseText.my_photo_permissions_count+')');
          }
          $(this).html(li_content).fadeTo(300,1);
          if(responseText.js){
            eval(responseText.js);
          }
        });
      }
    });
  });
  
  $('.tabs > ul > li > a[href*=photos]').click(function () {
    document.location = this.href;
  })
  
  //Voicemail ID Info Bubble

  $("#details .voicemail_id").hover(function() {
    $(this).children(".hoverinfo").fadeIn(100);
  }, function() {
    $(this).children(".hoverinfo").fadeOut(100);
  });
  
  //Help Text Bubbles
  
  $("input,textarea").focus(function () {
    try {
      bubble_id = $('#'+this.id).parent()[0].id;
      if (bubble_id) { $('.'+bubble_id).fadeIn(150); }
    } catch(e) {
    }
  })
  
  $("input,textarea").blur(function () {
    try {
      bubble_id = $('#'+this.id).parent()[0].id;
      if (bubble_id) { $('.'+bubble_id).fadeOut(150); }
    } catch(e) {
    }
  })

  if ($('#report').length > 0) {
    $('#report').jqm();
  }
  
  $('a.jqReport').click(function() { 
    $('html').animate({scrollTop:0}, 'fast');
    return false;
  });
  
  //jqModal Alerts
  $('#alert').jqm({overlay: 0, modal: true, trigger: 'false'});
  $('a.alert').click(function() { 
    $('html').animate({scrollTop:0}, 'fast');
    $('.jqmAlertWindow:first')
      .find('div:first')
        .removeClass('jqmNoticeTitle')
        .addClass('jqmAlertTitle');
    alert('This feature is coming soon!');     
    return false;
  });
  
  
  // display an alert message
  function alert(msg) { 
 	  $('#alert')
  	  .find('div > div:first')      
        .removeClass('jqmAlertTitle')
        .addClass('jqmNoticeTitle');
    $('#alert')
  		.jqmShow()
  		.find('div.jqmAlertContent') 
  			.html(msg); 
  }

  // Table Cell Hover States
  $(".clickable").hover(function() {
			$(this).addClass("highlight");
		}, function() {
			$(this).removeClass("highlight");
		}
	);

  // Clickable Table Cell
	$("#my_favorites_list .clickable").click(function(e){
	  e.preventDefault();
	  
	  div_url = $(this).attr('href');
	  if (String(e.target).substr(0,7) == 'http://') {
	    target_url = e.target;
	  } else {
	    target_url = div_url;
	  };
	
  	window.location = target_url;
	});
	
}
function _search_init() {
  //Search Sliders
  min = $("#min_search_distance")[0];
  minv = min ? min.value : 0;
  max = $("#max_search_distance")[0];
  maxv = max ? max.value : 0;
  
  $("#distance_slider").slider({
    min: 0,
    max: 500,
    stepping: 25,
    range: true,
    values: [minv, maxv],
    slide: function(e, ui) {
      min = $("#distance_slider").slider("values", 0);
      max = $("#distance_slider").slider("values", 1);
      $("#distance_slider_label").html(min + "-" + max);
    },
    change: function(e, ui) {
      $("#min_search_distance")[0].value = $("#distance_slider").slider("values", 0);
      $("#max_search_distance")[0].value = $("#distance_slider").slider("values", 1);
    }
  });

  min = $("#min_search_age")[0];
  minv = min ? min.value : 20;
  max = $("#max_search_age")[0];
  maxv = max ? max.value : 35;

  
  // Search view toggle
  function update_pagination_links(from, to) {
    $('#pagination .pagination a').each(function(i,a){
      if (a.href.search(from) < 0) {
        a.href = a.href + "&" + to;
      } else {
        a.href = a.href.replace(from, to);
      }
    });
  }
  $('#sort .view_list').click(function(e){
    $(this).addClass('selected');
    $('#sort a.view_gallery').removeClass('selected');
    e.preventDefault(); // ignore click
    $('#search_results').removeClass('gallery');
    $('#search_results').addClass('list');
    $('#search_result_style')[0].value = 'list';
    update_pagination_links('style=gallery', 'style=list');
  });
  $('#sort .view_gallery').click(function(e){
    $(this).addClass('selected');
    $('#sort a.view_list').removeClass('selected');
    e.preventDefault(); // ignore click
    $('#search_results').addClass('gallery');
    $('#search_results').removeClass('list');
    $('#search_result_style')[0].value = 'gallery';
    update_pagination_links('style=list', 'style=gallery');
  });
  
  
  // Search result extra selectors
  $('.search_picker').each(function(i,e){
    $(e).change(function(ee){
      field = $("#" + e.id.slice(0, -7))[0]; // trim _picker from id
      field.value = e.value;
      $('#search_form button[type=submit]').trigger('click');
    });
  });
  
  //Search Filter Collapsing Menus
  $('#filter_options ul').filter(':not(:first)').filter(':not(:has(:checked))').hide();
  $('#filter_options li.category h4').hover(
    function() {
		// over
			$(this).addClass("over");
		},
		function() {
		// out
			$(this).removeClass("over");
		}
  );
  $('#filter_options li.category h4').click(
    function() {
      $(this).next().slideToggle('normal');
    }
  );
  
  // Search Filter Count Updates
  $('#filter_options li.category .checkbox').click(function(){
    group = this.name.slice(0, -2);
    checked = $('#filter_options .checkbox[name^='+group+']:checked').length || "0";
    $('#'+group+'_count').html(checked);
  });
  function keywordsEntered(){
    if ($('#filter_options').length > 0) {
      form_value = $('#filter_options input.keywords')[0].value;
      if (form_value && $.trim(form_value) != '') {
        result = 'Entered';
      } else {
        result = 'None Entered';
      }
      $('#keywords_entered').html(result);
    }
  }
  $('input.keywords').blur(function() {
    keywordsEntered();
  })
  keywordsEntered();
  
  // Search Profile Hover States
  $(".clickable").hover(function() {
			$(this).addClass("highlight");
		}, function() {
			$(this).removeClass("highlight");
		}
	);

  // Clickable Search Results
	if (!$('#complete_signup').length > 0) {
  	$("#search_results .clickable").click(function(e){
  	  e.preventDefault();
  	    	  
  	  div_url = $(this).attr('href');
  	  
  	  if (String(e.target).substr(0,7) == 'http://') {
  	    target_url = e.target;
  	  } else {
  	    target_url = div_url;
  	  };
  	  
   	  per_page   = $('#search_result_per_page_picker > option:selected').val();

  	  page       = $.query.get('page');
  	  if (page == '') { page = '1'; }
  	  
      $('.clickable').each( function(i, elem) {
        if ($(elem).attr('href') == div_url)
          {pos = i + 1;} 
      });

      $.cookie('search_click', page+','+per_page+','+pos);
      $.cookie('search_referer', window.location.href);

    	window.location = target_url;
  	});
  	
	};

  function fade_prev_next(position, total) {
    prev = $('#browse_bar').find('button.prev');
    next = $('#browse_bar').find('button.next');

    if (position == 0 && prev.css('opacity') != '0.3') {
      prev.fadeTo('fast', 0.3);
    } else if (position != 0 && prev.css('opacity') != '1') {
      prev.fadeTo('fast', 1);
    }
    
    if (position == total && next.css('opacity') != '0.3') {
      next.fadeTo('fast', 0.3);
    } else if (position != total && next.css('opacity') != '1') {
      next.fadeTo('fast', 1);
    }
    
    $("#notification_message").html('');
  }
	
	function move_browse(direction) {
	  profiles = $('#browse_profiles > .browse_profile');
    ordered_profile_logins = $.map(profiles, function (a) { return a.id });
    
    profile_to_hide       = $('.browse_profile:visible:first')[0];
    hide_position         = $.inArray(profile_to_hide.id, ordered_profile_logins);
    profiles_remaining    = ordered_profile_logins.length - (hide_position+2);
    show_position         = hide_position+direction;
    
    // check for out of bounds
    if (show_position < 0) { show_position = 0; }
    if (show_position > ordered_profile_logins.length - 1) { show_position = ordered_profile_logins.length - 1; }
    
    profile_to_show       = profiles[show_position];
    
    $(profile_to_hide).hide();
    $(profile_to_show).show();
    
    fade_prev_next(show_position, ordered_profile_logins.length - 1);

    $.cookie('search_browse_profile', $('.browse_profile:visible:first')[0].id);

    // load more profiles as required
		if (profiles_remaining == 5) {
			$.get("/search/browse?offset="+ordered_profile_logins.length,function(data){
				$('#browse_profiles').append(data);
			});
		}
        
    //console.log(ordered_profile_logins);
		//console.log('showing: '+current_position+' - remaining: '+(ordered_profile_logins.length - (current_position+2)));
	}
	
	$('button.next, button.prev, .link.next').livequery('click', function(e) {
	  e.preventDefault(); //disable the click
    if ($(this).hasClass('prev')) {
		  move_browse(-1);
		} else {
		  move_browse(1);
		}
	});
	
	$('#browse_bar > div > a.message_me').livequery('click', function(e) {
	  e.preventDefault(); //disable the click
	  document.location = '/profiles/'+$('.browse_profile:visible:first')[0].id+'/new_message';
	});

}
function _signup_init() {
  // Add onchange handlers for imported fields
  $(".imported input, .imported select").change( function() { $(this).parent(".imported").removeClass("imported"); } );

  // don't do this for IE 6
  if (!$.browser.msie || $.browser.version >= 7.0) {  
    if ($('#complete_signup').length > 0) {
      $('#complete_signup').jqm({
  			trigger: '#search_results .result, #search_results .result >*,#pagination .pagination > *, #general button',
  			onShow: function(hash) {
  			  hash.w.show();
          $('html').animate({scrollTop:0}, 'fast');
  			}
  		});
    }
    
    $('#complete_signup .signup_form_body #user_login').keyup(function () {
      value = this.value;
      if (this.value != this.lastValue) {
        if (this.timer) clearTimeout(this.timer);
        $('#user_login_validation').html('<img src="/images/wait.gif" height="16" width="16" /> checking');
      
        this.timer = setTimeout(function () {
          $.ajax({
            url: '/users/validate',
            data: 'user[login]=' + value,
            type: 'post',
            success: function (response) {
              $('#user_login_validation').html(response);
              if (response.search('unavailable') == -1) {
                $('#user_login').removeClass('error');
              } else {
                $('#user_login').addClass('error');
              }
            }
          });
        }, 500);
      
        this.lastValue = this.value;
      }
    }); 
  }
}
function _messages_init() {
	
	// Ajaxify delete individual message from in-/sent-box index
	$("#message_index a.msg_delete").livequery('click', function(e){
    e.preventDefault();
    $(this).parent().parent().fadeTo("normal", 0.33);
    
    url_bits = new Array;
    msg_ids  = new Array;
    url_bits = this.href.split('/');
    url_bits.pop();               // discard the last element
    msg_ids.push(url_bits.pop()); // use the second last element
    
    delete_msgs(msg_ids);
  });

  // Delete all marked messages
  $('#actions a.delete_all').click(function (e) {
    e.preventDefault();
    
    msg_ids = new Array;
    $('#message_index input:checked').parent().parent().each(function() { msg_ids.push($(this).attr('id').split('-').pop()); })     
    
    delete_msgs(msg_ids);
  });

  // Delete one or more messages
  function delete_msgs(msg_ids) {
    try { page = $.query.get('page');     } catch(err) { page = 1;    }; // which page are we on?
    try { filter = $.query.get('filter'); } catch(err) { filter = ''; }; // msg filters?
    context = document.location.pathname.split('/')[2]            // inbox or sent?
    
    $.ajax({
      type: "DELETE",
      dataType: 'json',
      url: '/messages/delete',
      data: 'msg_ids='+msg_ids.toString()+'&page='+page+'&context='+context+'&filter='+filter,
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      },
      beforeSend: function(){
        $("#notification_message").fadeTo("normal", 0.33);
      },
      success: function(json){
        $("#notification_message").html(json.status_message);
        $("#notification_message").fadeTo("fast", 1);
        
        $("#message_index").html(json.html);

        $("#message_types option").removeAttr("selected"); // reset the drop down options
        
        if (json.unread.messages == 0 && json.unread.flirts == 0) {
          document.location = '/messages/inbox';
        } else {
          update_message_counts(json.unread.messages, json.unread.flirts);
        }
      }
    });
  }


  // mark all marked messages as read
  $('#actions a.mark_all_read').click(function (e) {
    e.preventDefault();
    read_unread('read')
  });
  
  // mark all marked messages as unread
  $('#actions a.mark_all_unread').click(function (e) {
    e.preventDefault();
    read_unread('unread')
  });
  
  
  function update_message_counts(messages, flirts) {
    $('div.unread.png').html(messages);
    $('#sidebar_inbox').html("Inbox ("+messages+")");
    $('span.count').html(messages);
    $('#sidebar_flirts').html("Flirts ("+flirts+")");
  }
  
  // mark/unmark messages as read
  function read_unread(style) {
    try { page = $.query.get('page');     } catch(err) { page = 1;    }; // which page are we on?
    try { filter = $.query.get('filter'); } catch(err) { filter = ''; }; // msg filters?
    context = document.location.pathname.split('/')[2]            // inbox or sent?
    
    msg_ids = new Array;
    $('#message_index input:checked').parent().parent().each(function() { msg_ids.push($(this).attr('id').split('-').pop()); })     
  
    $.ajax({
      type: "POST",
      dataType: 'json',
      url: '/messages/read_unread',
      data: 'msg_ids='+msg_ids.toString()+'&page='+page+'&context='+context+'&read_unread='+style+'&filter='+filter,
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      },
      beforeSend: function(){
        $("#notification_message").fadeTo("normal", 0.33);
      },
      success: function(json){
        $("#notification_message").html(json.status_message);
        $("#notification_message").fadeTo("fast", 1);

        $("#message_index").html(json.html);
        
        $("#message_types option").removeAttr("selected"); // reset the drop down options
        
        if(json.unread){
          update_message_counts(json.unread.messages, json.unread.flirts);
        }
      }
    });
  }

	// checkbox select from drop down
  if ($('#message_types').length > 0) {
    $('#message_types').change(function() { 
      var message_index 

      message_index = $("#message_types").val(); 

      if (message_index == 'All') {
        // select all
        checkAll();
      } else if (message_index == 'Read') {
        // select read messages
        uncheckAll();
        $('tr.msg_read').find('input.checkbox').attr('checked', true);
       } else if (message_index == 'Unread') {
        // select unread messages
        uncheckAll();
        $('tr.msg_unread').find('input.checkbox').attr('checked', true);
      } else if (message_index == 'None') {
        // deselect all messages
        uncheckAll();
      }

      return false;
    })
  }

  function checkAll() {
    $("#message_index input:checkbox").attr('checked', true);
  }

  function uncheckAll() {
    $("#message_index input:checkbox").attr('checked', false);
  }


  // Table Cell Hover States
  $(".clickable").hover(function() {
			$(this).addClass("highlight");
		}, function() {
			$(this).removeClass("highlight");
		}
	);


	$(".clickable td input").click(function(e){
	  e.stopImmediatePropagation();
	  
	});

  // Clickable Table Cell
	$(".message_list-v2 .clickable").click(function(e){
	  e.preventDefault();
	  
	  
	  div_url = $(this).attr('href');
	  if (String(e.target).substr(0,7) == 'http://') {
	    target_url = e.target;
	  } else {
	    target_url = div_url;
	  };
	
  	window.location = target_url;
	});
	

  	

}
function _new_message_init() {
  
  $('#new_message_form').ajaxForm({dataType:'script'})
  
  $(".result").hover(function() {
      if (!$(this).is('.disabled_gift'))
        $(this).addClass("highlight");
    }, function() {
      $(this).removeClass("highlight");
    }
  );
  
  // default none selected
  var clear_attachments = function() {
    $('#message_attachable_class')[0].value = ""
    $('#message_attachable_id')[0].value = ""
    $('#message_type')[0].value = $('#gift_to_self')[0] ? "GiftMessage" : "Message"
    
    $('.paperclip').hide()
    $('#has_attachment').hide()
  }

  // Enabling this will sill screw-up photo messages/comments! http://redmine.almlabs.com/issues/1002922
  //clear_attachments()
  
  $('.attachable_gift').livequery('click', function(e) {
	  e.preventDefault(); //disable the click
	  // clear_attachments()
	  clear_attachments()
    $('#adding_a_gift').hide()
    
    $(this).find('.paperclip').show()
    $('#has_attachment').show()

    $('#attached_gift_name').text($(this).find('.gift_title').text())
    
    $('#attached_gift_image').hide()
    $('#attached_gift_image')[0].src = $(this).find('.thumb img').attr('src')

    $('#message_type')[0].value = "GiftMessage"
    $('#message_attachable_class')[0].value = "Gift"
    $('#message_attachable_id')[0].value = $(this).attr('gift_id')
    
    $('#gift_added').show()
    $('#attached_gift_image').fadeIn()
	});
	
	$('.show_all_gifts').livequery('click', function (e) {
	  e.preventDefault(); //disable the click
	  $('.show_all_gifts').hide()
	  //$('#more_gifts').slideDown('slow')
		$('#more_gifts').show()
	})
	
	$('#remove_gift_button').livequery('click', function (e) {
	  e.preventDefault(); //disable the click
    clear_attachments()	  
	  $('#adding_a_gift').show()
	  $('#gift_added').hide()
	})
}
function _reply_message_init() {
  $('#reply_form form').ajaxForm({dataType:'script'})
}
function _private_init() {
  $('#private_thumbnail').live("click", function(e){
    e.preventDefault(); //disable the click
    $.get($(this).attr('href'), function(data){location = '?t=photos_private'});
    return false;
  });
  
  
  // Ajaxify message buttons
  $("#message_photo_permissions a.delete, #message_photo_permissions a.create").live('click', function(e){
    e.preventDefault();
    if( $(this).hasClass('delete') || $(this).hasClass('ajax_hide_on_btn_push')){$(this).parent().parent().fadeOut()}
    $.ajax({
      url: this.href,
      dataType: 'json',
      type: this.type,
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      },
      beforeSend: function(){
        $("#notification_message").fadeTo("normal", 0.33);
      },
      success: function(json){
        if (json.status_message != undefined) {
          $("#notification_message").html(json.status_message);
          $("#notification_message").fadeTo("fast", 1);
        }
        if (json.humanized_amount_of_access_remaining != undefined) {
          $("#humanized_access_time").html(json.humanized_amount_of_access_remaining);
          $("#humanized_access_time").fadeTo("fast", 1);
        }
      }
    });
  });
}
function _voicemails_init() {

  function playSound(vm_id, url) {
    soundManager.createSound({
      id:'voicemail_'+vm_id,
      url:url,
      onplay:function() {
        $('#vm_'+vm_id).removeClass('play');
        $('#vm_'+vm_id).addClass('pause');
      },
      onfinish:function() {
        $('#vm_'+vm_id).removeClass('pause');
        $('#vm_'+vm_id).addClass('play');
      }
    }).play();
    return false;
  }

  $("a.play").livequery('click', function(e){
    e.preventDefault();
    
    id = this.href.split('/').pop();
    
    if (id == '0') {
      playSound('0', '/mp3/voicemail_welcome.mp3');
    } else {    
      $.getJSON('/voicemails/play/'+id, function(result) {
        // update msg counts, etc., if this is a new message
        if($('#vm_'+id+'_new').length > 0) {
          $('#vm_'+id+'_new').fadeOut();
          if (result.new_voicemails > 0) {
            $('.unread_voicemails').html(result.new_voicemails);
          } else {
            $('.unread_voicemails').fadeOut();
          }
          $('#inboxlinks > a[href=/voicemails]').html('Voicemails ('+result.new_voicemails+')');
        }
        // play the message
        if (result.href) {
          playSound(id, result.href);
        } else {
          alert(result.message);
        }
      })
    }    
    return false;
  });
 
  $("a.pause").livequery('click', function(e){
    e.preventDefault();
    $(this).removeClass('pause');
    $(this).addClass('play');
    soundManager.pauseAll();
    return false;
  });

 
   // Table Cell Hover States
  $(".clickable").hover(function() {
			$(this).addClass("highlight");
		}, function() {
			$(this).removeClass("highlight");
		}
	);	
	
	
	//jqModal Alerts
  $('#alert').jqm({overlay: 0, modal: true, trigger: 'false'});

	// display an alert message
  function alert(msg) {
    $('#alert')
  		.jqmShow()
  		.find('div.jqmAlertContent') 
  			.html(msg); 
  }
 
  
}
function _lists_init() {
  // Ajaxify favorites remove from list
  $("#my_favorites_list a.delete").click(function(e){
    e.preventDefault();
    $(this).parent().parent().parent().parent().fadeOut();
    $.ajax({
      type: "DELETE",
      url: this.href,
      dataType: 'json',
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      },
      success: function(responseText, statusText) {
        if (responseText.my_favorites_count != undefined) {
          $('#my_favorites_link').html('My Favorites ('+responseText.my_favorites_count+')');
        }
      }
    });
    return false;
  });
  // Ajaxify block remove from list
  $("#block_list a.delete").click(function(e){
    e.preventDefault();
    $(this).parent().parent().fadeOut();
    $.ajax({
      type: "DELETE",
      url: this.href,
      dataType: 'json',
      error: function(XMLHttpRequest, textStatus, errorThrown) {
      },
      success: function(responseText, statusText) {
      }
    });
    return false;
  });
  
  function update_permissions_tabs(responseText){
    if (responseText.private_access_requested != undefined) {
      $('#requested_permission_tab').html('Requested ('+responseText.private_access_requested+')');
    }
    if (responseText.private_access_total_count != undefined) {
      $('#sidebar_private_access').html('Private Access ('+responseText.private_access_total_count+')');
    }
    if (responseText.private_access_granted != undefined) {
      $('#granted_permission_tab').html('Granted ('+responseText.private_access_granted+')');
    }
    if (responseText.private_access_as_viewer_granted != undefined) {
      $('#accepted_permission_tab').html('Access ('+responseText.private_access_as_viewer_granted+')');
    }
    if (responseText.private_access_as_viewer_requested != undefined) {
      $('#pending_permission_tab').html('Pending ('+responseText.private_access_as_viewer_requested+')');
    }
  }

  // Ajaxify permissions
  $("#photo_permissions a.delete, #photo_permissions a.create").live('click', function(e){
    e.preventDefault();
    $(this).parent().parent().fadeOut();
    $.ajax({
      url: this.href,
      dataType: 'json',
      type: this.type,
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      },
      beforeSend: function(){
        $("#notification_message").fadeTo("normal", 0.33);
      },
      success: function(responseText, statusText) {
        update_permissions_tabs(responseText);
        if (responseText.private_access_granted_html != undefined) {
          $('#granted_permission .private-photo-info p.last').html( 'You have <b>Granted Access</b> to your Private Gallery to these user(s).' );
          $('#granted_permission table.private-photos tbody').prepend( responseText.private_access_granted_html );
        }
        if (responseText.status_message != undefined) {
          $("#notification_message").html(responseText.status_message);
          $("#notification_message").fadeTo("fast", 1);
        }
      }
    });
  });
  
  $("#photo_permissions a.update").live('click', function(e){
    var thing_clicked= $(this)
    e.preventDefault();
    $.ajax({
      url: this.href,
      data: {}, // this is a hack for FireFox 3.0 (http://itmeze.com/2009/07/firefox-3-0-411-length-required-with-jquery/)
      dataType: 'json',
      type: 'PUT',
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // report_error(XMLHttpRequest.responseText);
      },
      success: function(responseText, statusText) {
        update_permissions_tabs(responseText);
        if (responseText.private_access_increased_html != undefined) {
          $(thing_clicked).parent().parent().find('td.duration').html(responseText.private_access_increased_html)
        }
        
      }
    });
  });
  
 
}
function _profile_edit_init() {
  
  function changeZipPost() {
    country_code = $('#profile_country').val();
    if (country_code == 'US') {
      zippost = 'Zip Code';
      stateprovince = 'State';
    } else if (country_code == 'GB') {
      zippost = 'Postcode';
      stateprovince = 'County';
    } else if (country_code == 'CA') {
      zippost = 'Postal Code';
      stateprovince = 'Province';
    } else if (country_code == 'AU') {
      zippost = 'Postcode';
      stateprovince = 'State';
    } else {
      zippost = 'Zip/Postcode';
      stateprovince = 'State/Province'
    }
    $('#zip_post > label').html(zippost);
    $('#state_province > label').html(stateprovince);
  }

  changeZipPost();

  // update your pre-approval profile
  $("#content > #approval, #content > .tabs > #profile").find("button").click(function (e) {
    e.preventDefault();
    form    = $(this).parents('form');
    values  = form.serialize();
    url     = form[0].action;

    form_id = form[0].id;

    $.ajax({
      type: "POST",
      url: url,
      dataType: 'json',
      data: values+'&form_id='+form_id,
      error: function(XMLHttpRequest, textStatus, errorThrown) {
      },
      beforeSend: function(){
        form.find('input,textarea,select').removeClass('error');
        $('p.error').remove();
      },
      success: function(json){
        if (json.message) {
          form.prepend(json.message);
          setTimeout("form.children('p.updated').fadeOut('slow');",1400);
        
          if (json.section_complete) { setTimeout("form.parent().slideUp('normal', function() {form.parent().siblings().addClass('done');}); ", 1400); }
                
          if (json.sidebar) {
            $('#sidebar').html(json.sidebar);
            if (json.profile_complete) {
              // profile is now complete
              $('#profile_sections').slideUp('normal', function () {
                $('#approval_notice').fadeOut('normal', function() {
                  $(this).html(json.profile_complete);
                  $('#approval_notice').fadeIn();
                })
              });
            }
          }
          if (json.redirect_to) {
            window.location = json.redirect_to;
          }
        } else {
          error_keys = json.error_keys.split('/');
          $.each(error_keys, function(index, value) {
            field_name = value.replace(' ', '');
            field = $('[id*='+field_name+']:first');
            field.addClass('error');
            if(field.parent().children('p.error:first')[0] == null){
              field.before('<p class="error">'+json[field_name]+'</p>');
            } else {
              field.parent().children('p.error:first').text(json[field_name]);
            }
          })
        }
      }
    });
  })
  
  
  
  $('#mass_save').click(function(e){
    $('form p.submit-area button').each(function(b) {
      $(this).click()
    })
  })
}
function _packages_init() {
  $('.package.preferred').click(
    function(e){
      $(this).find('input.radio').attr('checked', 'checked').change();
    }
  );

  // For copying our billing address to the shipping address
  var show_shipping_form = function(e) {
    if ($('#shipping_same_billing')[0] != null) {
      if ($('#shipping_same_billing')[0].checked) {
        $('#promotion_shipping_fields').hide()
      } else {
        $('#promotion_shipping_fields').show()
      }    
    }
  }
  show_shipping_form()
  
  $('#shipping_same_billing').click(show_shipping_form)
  
  // selected package bg toggle
  $('.package .footer input').change(function() {
    $('.package .footer label').removeClass('selected');
    $(this).siblings('label').addClass('selected');
    

    // Determine if we should show the shipping form
    if ($(this).attr('requires_shipping') && $(this).attr('requires_shipping') == "true") {
      $('#promotion_shipping_form').show()
    } else {
      $('#promotion_shipping_form').hide()
    }
    
    $('#payment_method').show()
    update_amounts();
    
    $('.packages_alt').hide()
    
    // make sure the visible form elements are non-disabled upon page reloads
    $('.repurchase:visible, .credit_card:visible').find(':input').removeAttr('disabled');
    $('.repurchase:hidden,  .credit_card:hidden' ).find(':input').attr('disabled', 'disabled');
  });

  //CHelp Bubbles  
  $("input,textarea").focus(function() {
    try {
      bubble_id = $('#'+this.id).parent()[0].id;
      if (bubble_id) { $('.'+bubble_id).fadeIn(150); }
    } catch(e) {
    }
  });
  
  $("input,textarea").blur(function() {
    try {
      bubble_id = $('#'+this.id).parent()[0].id;
      if (bubble_id) { $('.'+bubble_id).fadeOut(150); }
    } catch(e) {
    }
  });
    
	//jqModal
  if ($('#cvv').length > 0) {
    $('#cvv').jqm();
  }  
  
  // make sure the submit buttons aren't disabled by default
  $('#content').find('button').removeAttr('disabled');

  // set default
  $('.package .footer input:checked').change();

  // changing button image, and disable additional clicks upon button click
  $('#content').find('button').click(function (e) {
    if ($(this).closest('.repurchase').length > 0 && $("input[name='previous_credit_card_id']:checked").length < 1)  {
      e.preventDefault();
      alert('Please select a credit card');
    } else if ($(this).is('.processing')) {
      e.preventDefault();
    } else {
      $('#content').find('button').addClass('processing');
    }
  });
  
  // Init Accordion
  $("#accordion").accordion({ autoHeight: false });  
  $('#accordion').bind('accordionchange', function(event, ui) {
    // disable the hidden form elements
    ui.newContent.find(':input').removeAttr('disabled');
    ui.oldContent.find(':input').attr('disabled', 'disabled');
    update_amounts();
  });
  // make sure the visible form elements are non-disabled upon page reloads
  $('.repurchase:visible, .credit_card:visible').find(':input').removeAttr('disabled');
  $('.repurchase:hidden,  .credit_card:hidden' ).find(':input').attr('disabled', 'disabled');

  // Tax Calculations, Price Display
  function update_amounts() {
    var pkg_id = null;
    
    var checked_sub = $("input[name='subscription[subscription_package_id]']:checked")
    var checked_cred = $("input[name='credit_package_id']:checked")
    
    if ($('#subscription_subscription_package_id')[0]) {
      pkg_id = $('#subscription_subscription_package_id')[0].value;
    } else if (checked_sub && checked_sub.length > 0) {
      pkg_id = checked_sub[0].value;
    } else if (checked_cred && checked_cred.length > 0) {
      pkg_id = checked_cred[0].value;
    }

    if (pkg_id != null) {
      base_price = tax_amounts[pkg_id]['base'];
     
      if ($('.repurchase:visible')[0] && $("input[name='previous_credit_card_id']:checked")[0]) {
        id = $("input[name='previous_credit_card_id']:checked")[0].value;
        tax_price = tax_amounts[pkg_id]['repurchase-'+id];
      } else if ($('#credit_card_province:visible')[0]) {
        tax_price = tax_amounts[pkg_id][$('#credit_card_province')[0].value];
      } else {
        tax_price = 0;
      }
      $('.payment_totals .base_val').html(base_price.toFixed(2));
      $('.payment_totals .tax_val').html(tax_price.toFixed(2));
      $('.payment_totals .total_val').html((base_price + tax_price).toFixed(2));
    }
  }

  $('#credit_card_province').change(function (e) {
    // If we're filling out a new subscription, calculate tax for selected province
    update_amounts();
  });
  $("input[name='previous_credit_card_id']").click(function (e) {
    update_amounts();
  });
  $('#credit_card_country').change(function (e) {
    // Display province/state field if country is canada
    if (this.value == 'CA') {
      $('#credit_card_province')[0].disabled = false;  
      $('#credit_card_province').parent('p').show();
      $('.credit_card .tax_val').closest('tr').show();
      $('#credit_card_state')[0].disabled = true;
      $('#credit_card_state').parent('p').hide();
    } else {
      $('#credit_card_province')[0].disabled = true; // prevent from being submitted in the form
      $('#credit_card_state')[0].disabled = false;
      $('#credit_card_state').parent('p').show();
      $('#credit_card_province').parent('p').hide();
      $('.credit_card .tax_val').closest('tr').hide();
      $('.credit_card .total_val').html($('.base_val').html());
    }
    $('#credit_card_province').change();
  });

  // update default pricing
  $('#credit_card_country').change();
  $('.package .footer input:checked').change();
  
}
function _credits_init() {
  _packages_init()
  
  $('#buy_credits_form').ajaxForm({dataType:'script',
                                    beforeSubmit: function(arr, form, options) {
                                      $('.error').hide()
                                    },
                                    error: function(){
                                      alert('There was an error with your request. Please try again.')
                                      $('#content').find('button').removeClass('processing');
                                    }});
}
function _subscriptions_init() {
  $('#payment_method').show()
  _packages_init()
}
function _flirts_init() {

  // show modal, and fill with content
  $('#alert').jqm({overlay: 0, modal: true, trigger: 'false'});

  // search/browse
  $('#browse_bar > div > a.jqmTrigger').livequery('click', function() {
    login = $('.browse_profile:visible:first')[0].id;
    startFlirting(login);
  });

  // profiles/show, profile_favorites/index
  $('a.flirt').click(function() {
    login = $(this)[0].href.split('/')[4];
    startFlirting(login);
    return false;
  });

  function startFlirting(login) {
    $('html').animate({scrollTop:0}, 'fast');

    $('#modals').empty();
    $('#modals').html('<div id="flirt" class="jqmWindow"></div>');
    
    $("#notification_message").html('');
    
    if ($.query.get('pnum') != '') {
      query_params = '?pnum='+$.query.get('pnum');
    } else {
      query_params = '';
    }
    
    var url = '/profiles/'+login+'/flirts/new.json'+query_params;

    $.getJSON(url, function(result){
      if (result.style == 'modal') {
        $('#flirt')
          .jqm()
          .html(result.content)
          .jqmShow();
      } else {
        alert(result.content);
      }
    })
    return false;
  };

  // submit flirt form, and deal with response from server
  $('form[name="send_flirt"]').livequery(function() {
    $(this).ajaxForm({dataType: 'json',
      dataType: 'json',
      beforeSend: function() {
        $("#notification_message").empty();
        $('form[name="send_flirt"]').find('button')
          .attr('disabled', 'disabled')
          .fadeTo('fast', 0.3)
        $('form[name="send_flirt"]').find('.centered.last')  
          .append('<img src="/images/wait.gif" height="16" width="16" />');
      },
      success: function(json){    
        $("#notification_message").html(json.message);
        $('#flirt').jqmHide();
      }
    });
  });

  
  // display an alert message
  function alert(msg) { 
 	  $('#alert')
  	  .find('div > div:first')      
        .removeClass('jqmAlertTitle')
        .addClass('jqmNoticeTitle');
    $('#alert')
  		.jqmShow()
  		.find('div.jqmAlertContent') 
  			.html(msg); 
  };

    
}
function _report_profile_init() {
  
  $('#report_profile').ajaxForm({
    dataType: 'json',
    success: function(json){
      if(json.hasErrors) {
        elem = $('#report_profile').children('p');
        elem.hide();
        elem.html(json.status_message);
        elem.slideDown();
      } else {
        if(json.profileBlocked == 'on') {
          $('.profile_flag:last').attr('src', '/images/flag_block_a.png');
        }
        $('.btn_report').hide();
        $("#notification_message").html(json.status_message);
        $('#report').jqmHide();
      }
    }
  });

}
$('a.chat').click(function(){
  $.getScript(this.href);
  return false;
})

function initializeChatClient(user_login)
{
  //Wait for iJab to exist. Check every second...
  var wait_for_ijab_interval = setInterval(function(){
    if(typeof iJab == "undefined") return;
    
    clearInterval(wait_for_ijab_interval);

    iJab.addListener({
      onAvatarClicked: function(x,y,username,jid){
        location = '/profiles/' + username; //Link to profile
      },
      onMessageReceive:function(jid, message){
        closeUnwantedChatSessions(iJabConf['blocked_user_names']);
      }
    });

    if(!iJabConf['xmpp']['auto_login']){
      //Means the user has chat disabled
      return;
    }

    $("div#ijab").show();

    //Do not remove this! It helps safari resume the connection!
    iJab.setStatusText('');

    closeUnwantedChatSessions(iJabConf['blocked_user_names']);

    setInterval(function(){closeUnwantedChatSessions(iJabConf['blocked_user_names']);}, 5000)

    setInterval(function(){$.getScript('/chat_sessions/heartbeat');}, 60000);
  }, 1000);
}

function closeUnwantedChatSessions(blocked_user_names){
  if(typeof iJabConf == "undefined") return;

  var selector = '.ijab-panels .ijab-window-tab-wrap h4';
  
  // Remove blocked user sessions
  //
  iJabConf['blocked_user_names'] = blocked_user_names;

  if(blocked_user_names && blocked_user_names.length > 0){
    $(selector).each(function(idx, e){
      var user_name = $(e).text();
      if($.inArray(user_name, blocked_user_names) > -1){
        closeChatSession(user_name);
      }
    });
  }

  // Too many chat sessions?
  //
  var els = $(selector);
  var count = els.length;
  var max = iJabConf['max_sessions'];

  els.each(function(idx, e){
    if(count <= max) return;
    closeChatSession($(e).text());
    count--;
  });
}

function closeChatSession(user_name){
  $(".ijab-window-tab-wrap:contains('" + user_name +  "') a.ijab-window-close").click();
  //$(".ijab-window-tab-wrap:contains('" + user_name +  "'), .ijab-window-window:contains('" + user_name + "')").remove();
}
