
function idea_users_action(action, arg1, arg2, params) {
  var uid = safe(Drupal.settings.idea_users.uid, 0);

  if (uid) {
    var href = '/idea-users/action/'+uid+'/'+action;
    if (arg1) { href += '/'+arg1; }
    if (arg2) { href += '/'+arg2; }
    params = params ? params : {};
    params.ajax = 1;
    jQuery.post(href, params, function(R) { idea_users_action_callback(R, action, arg1, arg2); }, "json");
  }
}

function idea_users_profile_action(ref_type, ref_id, action, params, callback) {
  if (ref_type && ref_id && action) {
    var href = '/idea-users/action/'+ref_type+'/'+ref_id + '/'+ action;
    var data = jQuery.extend({'ajax': 1}, (params ? params : {}));
    jQuery.post(href, data, function(R) {
      if (typeof (callback) == 'function') { eval(callback+'(ref_type, ref_id, action, data)'); }
    }, "json");
  }
}


function idea_users_action_callback(R, action, arg1, arg2) {
  //jQuery(".course-throbber", course).removeClass('throbbing');
  if (R.status) {
    if (action == 'set-acct' || action == 'set-accts') {
      for (i in R.data.html) {
        var acctBox = jQuery("#user-"+i+"-form-box");
        var updAcct = function() {
            var box = eval("R.data.html."+i+".box");
            jQuery("#user-"+i+"-wrap").empty().append(box);
            var link = eval("R.data.html."+i+".link");
            jQuery(".social-link."+i).replaceWith(link);
        };
        if (acctBox.size() > 0) {
          acctBox.fadeOut('fast', updAcct());
        }
        else {
          updAcct();
        }
      }
      if (action == 'set-accts') {
        jQuery("#GB_content").empty().append(R.data.html.thanks);
      }
    }
    else if (action == 'set-aid') {
      var aid = arg1;
      jQuery(".td-aid-"+aid).removeClass('throbbing');
      jQuery(".td-default-aid .default-wrapper").removeClass('is-default');
      jQuery(".td-aid-"+aid+" .default-wrapper").addClass('is-default');

      jQuery("#ajax-form-section-mbaddress_address_edit_form").replaceWith(R.data.default_address.form);
    }
    else if (action == 'delete-address') {
      address_remove_row(arg1);
    }
  }
}


function idea_users_on_set_twitter() {
  var val = jQuery("#edit-twitter-name").val();
  idea_users_action('set-acct', 'twitter', val);
}


function idea_users_on_set_social_links() {
  var fb = jQuery("#edit-acct-name-facebook").val();
  var tw = jQuery("#edit-acct-name-twitter").val();
  idea_users_action('set-accts', 'twitter--facebook', tw+'--'+fb);
}

function idea_users_init_social_links_form() {
  jQuery("#idea-users-social-links-form").submit(function() {
    idea_users_on_set_social_links();
    return false;
  });
}


function change_profile_image(src) {
  jQuery(".idea-user-profile-image .profile-image").attr('src', src);
}

function userProfilePicShowPreview(e, q, F, R) {
  var base_id  = String(e.target.id).replace('-uploadify', '');
  var queue_id = base_id + '-queue';

  var queue = jQuery("#"+queue_id +" .userUploadQueueComplete");
  jQuery(".uploadifyQueueItem", queue).hide();
  jQuery('#'+base_id + '-preview').append('<img width="100" src="/'+R.filepath+'" />');
}



function init_user_info_form() {
  //jQuery(".idea-user-save-changes").addClass('hidden');
}


function idea_users_update_pro_info(data) {
  idea_users_update_inline_form_preview(data);
}
function idea_users_update_acct_info(data) {
  idea_users_update_inline_form_preview(data);
}

function idea_users_update_inline_form_preview(data) {
  for (i in data) {
    elem = jQuery("#preview-"+i);
    if (elem.size() > 0) {
      elem.html(data[i]);
    }
  }
}



function address_row(aid, typ) {
  return jQuery(".address-"+typ+"-"+aid);
}

function address_expose_edit(aid) {
  var row_prev = address_row(aid, 'preview');
  var row_edit = address_row(aid, 'edit');
  row_prev.fadeOut(200, function() {
    row_edit.fadeIn(200);
  });
}
function address_show_preview(aid) {
  var row_prev = address_row(aid, 'preview');
  var row_edit = address_row(aid, 'edit');
  var fader = function() {
    row_edit.fadeOut(200, function() {
      row_prev.fadeIn(200);
    });
  };

  if (jQuery(".form-throbber", row_edit).size()) {
    jQuery(".form-throbber", row_edit).fadeOut(100, fader);
  }
  else {
    fader();
  }
}
function address_show_throbber(aid, typ) {
  var row = address_row(aid, typ);
  jQuery(".form-preview,.form-button", row).fadeOut(250, function() {
    jQuery(".form-throbber", row).addClass('throbbing').fadeIn(250);
  });
}
function address_hide_throbber(aid, typ) {
  var row = address_row(aid, typ);
  jQuery(".form-throbber", row).removeClass('throbbing').fadeOut(250, function() {
    var sel = (typ=='preview') ? '.form-preview' : '.form-button';
    jQuery(sel, row).fadeIn(250);
  });
}

function address_delete_address(aid) {
  address_show_throbber(aid, 'preview');
  idea_users_action('delete-address', aid);
}
function address_remove_row(aid) {
  var row_prev = address_row(aid, 'preview');
  var row_edit = address_row(aid, 'edit');
  row_prev.fadeOut(250, function() {
    row_prev.remove();
    row_edit.remove();
  });
}
function address_save_address(aid) {
  var f = jQuery('form', address_row(aid, 'edit'));
  f.submit();
}

function address_cancel_edit(aid) {
  aid = parseInt(aid);
  if (aid) {
    address_show_preview(aid);
  }
  else {
    address_remove_row(aid)
  }
}

function update_address_name(aid, val) {
  jQuery('.td-address-name', address_row(aid, 'preview')).html(val);
}
function update_address_disp(aid, val) {
  jQuery('.td-address-disp', address_row(aid, 'preview')).html(val);
}

function init_user_address_page() {
  jQuery('.default-wrapper .link a').click(function() {
    var aid = jQuery(this).attr('rel');
    jQuery(".td-aid-"+aid).addClass('throbbing');
    idea_users_action('set-aid', aid);
    return false;
  });

  jQuery("#user-addr-list .end .add-link").click(function() {
    var row_prev = Drupal.settings.idea_users.address.empty_row.preview;
    var row_edit = Drupal.settings.idea_users.address.empty_row.edit;
    jQuery("#user-addr-list-table tbody").append(row_prev).append(row_edit);
    init_user_address_init();
    address_expose_edit(0);
    return false;
  });

  init_user_address_init();
}

function init_user_address_init() {
  jQuery('.td-action-link a.edit:not(.processed)').each(function(index) {
    jQuery(this).click(function() { address_expose_edit(jQuery(this).attr('rel')); return false; }).addClass('processed');
  });
  jQuery('.td-action-link a.delete:not(.processed)').each(function(index) {
    jQuery(this).click(function() { if (confirm('Are you sure you want to delete this address?')) { address_delete_address(jQuery(this).attr('rel')); } return false; }).addClass('processed');
  });

  if (jQuery('select.idea-select').size() > 0) {
    ideaSelect();
  }

  jQuery('.edit-country:not(.idea-country-processed)').each( function () {
    idea_address_on_change_country(jQuery(this)[0]);
  });
  jQuery('.edit-country:not(.idea-country-processed)').change( function() {
    idea_address_on_change_country(jQuery(this)[0]);
    jQuery(this).addClass('idea-country-processed');
  });

  jQuery('.idea-btn-cancel:not(.processed)').each(function() {
    jQuery(this).css('display', 'block').click(function() {
      address_cancel_edit(jQuery('a', this).attr('rel'));
      return false;
    }).addClass('processed');
  });
}

function idea_address_init_ajax_addr() {
  jQuery('.edit-country:not(.idea-country-processed)').each( function () {
    idea_address_on_change_country(jQuery(this).get(0));
  });
  jQuery('.edit-country:not(.idea-country-processed)').change( function() {
    idea_address_on_change_country(jQuery(this).get(0));
  }).addClass('idea-country-processed');
}

function idea_address_on_change_country(country_sel) {
  var aid = jQuery(country_sel.form).attr('rel');
  var country = jQuery(country_sel).val();
  var row = jQuery(".address-edit-"+aid);
  if (country == 'us') {
    jQuery('.wrapper-province', row).hide();
    jQuery('.wrapper-state', row).show();
    jQuery('.wrapper-state .form-required', row).css({ 'display': 'inline'});
    jQuery('.wrapper-zip .form-required', row).css({ 'display': 'inline'});
   // jQuery('#wrapper-zip').show();
  }
  else {
    jQuery('.wrapper-province', row).show();
    jQuery('.wrapper-state', row).hide();
    jQuery('.wrapper-state .form-required', row).css({ 'display': 'none'});
    jQuery('.wrapper-zip .form-required', row).css({ 'display': 'none'});
  }
}


function dropdown_toggle_other_field(d, id) {
  var val = jQuery(d).val();
  if (val == 'other') {
    jQuery("#"+id).removeClass('hidden');
  }
  else {
    jQuery("#"+id).addClass('hidden');
  }
}


function idea_address_init() {

}



function idea_users_page_init() {
  if (typeof(Drupal.settings.idea_users) == 'undefined') {
    return;
  }

  jQuery("#idea-users-add-twitter-form").submit(function() {
    idea_users_on_set_twitter();
    return false;
  });

  init_user_info_form();
  init_user_address_page();

}

function idea_twitter_message(msg) {
  jQuery("#twitter_update_list").html('<li><span>'+msg+'</span></li>');
}

function idea_relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

var fbuids = {};
function idea_users_facebook_sync_accounts(fbuid, _profile) {
  var profile = _profile ? _profile : ((typeof(Drupal.settings.current_profile) != 'undefined') ? Drupal.settings.current_profile : 0);
  if (profile && profile.module && profile.data) {
    if (!(fbuids[profile.module + profile.data.id])) {
      fbuids[profile.module + profile.data.id] = fbuid;
      idea_users_profile_action(profile.module, profile.data.id, 'set-fbuid/'+fbuid);
    }
  }
}

function idea_users_facebook_attempt_sync() {
  if (typeof(FB) != 'undefined') {
    FB.getLoginStatus(function(response) {
      if (response.session) {
        idea_users_facebook_sync_accounts(response.session.uid);
      }
    });
  }
}


function idea_users_profile_switch(uid, profile) {
  var imgs = jQuery('.profile-switch-'+uid + '.profile-image');
  imgs.each(function() {
    var img = jQuery(this);
    var ic  = img.attr('data');
    var inf = String(img.attr('src')).split('/'+ic+'/');
    var path = inf[0] +'/'+ ic +'/'+ profile.picture;
    img.attr('src', path);
  });

  var names = jQuery('.profile-switch-'+uid + '.display-name');
  names.each(function() {
    jQuery(this).html(profile.display_name);
  });

  var items = jQuery('.profile-switch-'+uid);
  items.each(function() {
    var old = jQuery(this).attr('rel');
    jQuery(this).removeClass('type-'+old).addClass('type-'+profile.type).attr('rel', profile.type);
  });
  GB_throb_off();
}


if (Drupal.jsEnabled) {
  jQuery(document).ready(function() {
    idea_users_page_init();
  });
}
