// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$(function() {
	var searchBox2 = $("#prop_input.old").not("input.dashboard_prop_input");
	var searchBox2Default = "Start Here - type name of recipient";
	//Searchbox2 show/hide default text if needed  
	searchBox2.focus(function(){  
	    if($(this).attr("value") == searchBox2Default) $(this).attr("value", "");  
	});  
	searchBox2.blur(function(){  
	    if($(this).attr("value") == "") $(this).attr("value", searchBox2Default);  
	});
	
	var searchBox3 = $("#q, input.dashboard_prop_input");
	var searchBox3Default = "type name of recipient here";
	//Searchbox2 show/hide default text if needed  
	searchBox3.focus(function(){  
	    if($(this).attr("value") == searchBox3Default) $(this).attr("value", "");  
	});  
	searchBox3.blur(function(){  
	    if($(this).attr("value") == "") $(this).attr("value", searchBox3Default);  
	});

  var searchBox4 = $("#prop_input.new").not("input.dashboard_prop_input");
	var searchBox4Default = "type name of company or person";
	//Searchbox2 show/hide default text if needed
	searchBox4.focus(function(){
	    if($(this).attr("value") == searchBox4Default) $(this).attr("value", "");
	});
	searchBox4.blur(function(){
	    if($(this).attr("value") == "") $(this).attr("value", searchBox4Default);
	});
	
  $('div#header_login').hide();
  $('a#login_button').click(function () {
    $('div#header_login').toggle('blind');
    return false;
  });
  
  $('input#prop_submit').attr('disabled', 'true');
  
  $('input#prop_input, input#q').autocomplete('/search/results.js', 
    {
      formatResult: function(data) {
        return data[0].replace(/^.*?<em>([^<]*).*$/, '$1');
      },
      selectFirst: false,
      width: '220px',
      scrollHeight: '100%'
    });
    
  $('input#prop_input').result(function(event, data, formatted) {
    window.location = $(data[0]).attr('href');
  });
  
  if($('div.success').text().match(/Your prop was sent/)) {
    setup_referrals();
    auto = true;
  }
  else {
    auto = false;
  }
  
  
  $('div#referral_form').dialog({
    autoOpen: auto,
    modal: true,
    resizable: false,
    width: 481,
    position: 'center'
  });
  
  $('div#recent_props li').hover(
    function(event) {
      $(this).addClass('active');
    },
    function(event) {
      $(this).removeClass('active');
    }
  );
  
  setup_prop_non_user();
    
  $('.email_signatures>li').livequery('click', function(event) {
      event.preventDefault();
  });
  $('.email_signatures').bind("contextmenu",function(e){
      eval($('#signature_span_tracking').text());
  });
  $('.clippy').click(function(e){
      eval($('#signature_span_tracking').text());
  });


  if($('.success').text().match('The prop has been deleted.')){
      eval($('#hide_traking_code').text())
  }

  //plan change
  $('select[name=plan_id]').change(function(){
      if(this.value==''){
          $('#commit').attr('disabled',true);
      }else{
          $('#commit').attr('disabled',false);
      }
  })

  //tracking code for sign out
  $('.menu a').each(function (id,el){
      if($(el).text().toLowerCase()=='sign out'){
          $(el).click(function(e){
              eval($('#logout_span_tracking').text());
          })
      }
  });

  // colorpicker
  $(".colorpicker").gccolor({
    onChange: function(target,color) {
      var obj = $(target).attr('target');
      var attr = $(target).attr('target_attr');
      $(obj).css(attr,'#' + color);
    }
  });

  return false;
});



$('form#new_prop').livequery('submit', function(event) {
  event.preventDefault();
  if($('textarea#prop_message').val()) {
    if($('div#referral_form').length > 0) {
      setup_referrals();
    }
    submit_prop();
    $('div#referral_form').dialog('open');
  }
});


$('a#add_new_referral').livequery('click', function(event) {
  event.preventDefault();
  
  var fieldset = $('div#referral_form fieldset')[0];

  add_referral_fields($(fieldset).clone());
});

$('form#new_temporary_prop input#temporary_prop_name').livequery('focus', function(event) {
  var textdefault = "Name";
  
  if($(this).attr("value") == textdefault) $(this).attr("value", "");
});

$('form#new_temporary_prop input#temporary_prop_name').livequery('blur', function(event) {
  var textdefault = "Name";
  
  if($(this).attr("value") == "") $(this).attr("value", textdefault);
});
///////////////////////////////////
$('form#new_temporary_prop input#temporary_prop_email').livequery('focus', function(event) {
  var textdefault = "Email Address";
  
  if($(this).attr("value") == textdefault) $(this).attr("value", "");
});

$('form#new_temporary_prop input#temporary_prop_email').livequery('blur', function(event) {
  var textdefault = "Email Address";
  
  if($(this).attr("value") == "") $(this).attr("value", textdefault);
});
/////////////////////////////////

$('form#new_temporary_prop textarea').livequery('focus', function(event) {
  var textdefault = "Write your prop here.  Describe in detail what was done that was above and beyond your expectations.";
  
  if($(this).text() == textdefault) $(this).text("");
});

// $('form#new_temporary_prop textarea').livequery('blur', function(event) {
//   var textdefault = "Write your prop here.  Describe in detail what was done that was above and beyond your expectations.";
//   
//   if($(this).text() == "") $(this).text(textdefault);
// });

$('textarea#prop_message').livequery('focus', function(event) {
  var textdefault = /Describe in detail what .*? did to exceed your expectations?/;

  $('form#new_prop input#prop_submit').removeAttr('disabled');
  
  if($(this).val().match(textdefault)) {
   prop_message = $(this).val();
   $(this).val("");
 }
});


// $('textarea#prop_message').livequery('blur', function(event) {
//   if($(this).text() == "") $(this).text(prop_message);
// });


$('form#new_temporary_prop').livequery('submit', function(event) {
  event.preventDefault();
  
  if(validate_form()) {
    this.submit();
  }
});

$('a.show_prop_form').livequery('click', function(event) {
  event.preventDefault();
  
  $('form#new_temporary_prop').toggle();
});

$( function() {
  if(window.location.hash != "") {
    $('div.tab' + window.location.hash).addClass('active');
  }
  $('div.tab').each(function() {
    var tab = "<li><a href='" + $(this).attr('id') + "'>" + humanize($(this).attr('id')) + "</a></li>";

    if($('ul#settings_nav').length == 0) {
      $('div#inner_content').before('<ul id="settings_nav"></ul>');
    }

    var nav = $('ul#settings_nav');
    nav.append(tab);
    
  });

  var id = "";
  if($('div.error, div.success').parents('div.tab').length > 0) {
    id = $('div.error, div.success').parents('div.tab').attr('id');
  } else if($('div#inner_content div.active:first').length > 0) {
    id = $('div#inner_content div.active').attr('id');
  }
  
  if(id != "") {
    $('ul#settings_nav li a[href="' + id + '"]').parent('li').addClass('active');
  } else {
    $('ul#settings_nav li:first-child').addClass('active');
  }
  
  if($('div.tab').length > 0) {
    select_tab();
  }
});

$('ul#settings_nav a').livequery('click', function(event) {
  event.preventDefault();
  
  $('ul#settings_nav li').removeClass('active');
  
  $(this).parent('li').addClass('active');
  select_tab();
});

function select_tab() {
  var menu_item = $('ul#settings_nav li.active a')[0];
  menu_item = $(menu_item).attr('href');
  
  if(menu_item.match(/^http:.*$/)) {
    menu_item = menu_item.replace(/^.*\/([a-zA-Z0-9_-]*)$/, "$1");
  }
  $('div.tab').removeClass('active');
  $('div#' + menu_item).addClass('active');
  //for dynamic page traking
  var tracking_url  = $('#page_span_tracking').text().replace('||',menu_item);
  if(tracking_url){
      eval(tracking_url);
  }
}

function humanize(sentence) {
  return sentence.split('_').join(' ');
}

function setup_prop_non_user() {
  if($('ul.users, ul.companies').length > 0) {
    $('form#new_temporary_prop').hide();
    
    var not_found_text = $('p.not_found').text().replace(/(^.*?)(click here)(.*$)/, "$1<a href='#' class='show_prop_form'>$2</a>$3");
    $('p.not_found').replaceWith("<p class='not_found'>" + not_found_text + "</p>");
    
  }
}

function validate_form() {
  $('textarea#prop_message').removeClass('error');
  
  if(!$('input#temporary_prop_email').val().match(/^.*?@.*\.\w{2,3}$/)) {
    $('input#temporary_prop_email').addClass('error');
    $('p.not_found').hide();
    $('p.error').remove();
    $('div#messages').prepend('<p class="error">Oops... We will need a valid email address to continue.</p>');
    
    return false;
  }
  else {
    $('input#temporary_prop_email').removeClass('error');
    $('p.not_found').show();
    $('p.error').remove();
    
    return true;
  }
  
}

function setup_referrals() {
  var fieldset = $('div#referral_form fieldset')[0];
  
  $('div#referral_form fieldset').each(function() {
    $(this).remove();
  });
  
  add_referral_fields(fieldset);
  if($('a#add_new_referral').length == 0) {
    $('div#referral_form').append('<a href="#" id="add_new_referral">Add Another Referral</a>');
  }
  
  if($('a#no_thanks').length == 0) {
    $('div#referral_form input.blue_submit').after('<a href="#" id="no_thanks">No Thanks</a>');
    $('a#no_thanks').bind('click', function(event) {
      event.preventDefault();
      
      $('div#referral_form').dialog('close');
    });
  }
}

function add_referral_fields(fieldset) {
  
  $(fieldset).find('input[type="text"], textarea').each( function(index) {
    var field_name = humanize($(this).attr('name').match(/\w*(?=\]$)/)[0]);
    $(this).val(field_name);
    $(this).bind('focus', function() {
      if($(this).attr('value') == field_name) {
        $(this).attr('value', '');
      }
    });
  });
  
  $('div#referral_form form').append(fieldset);
}

function submit_prop() {
  
  var form = $('form#new_prop');
  $('input#prop_submit').attr('disabled', 'true');
  $.ajax({
    url: form.attr('action'),
    type: 'POST',
    dataType: 'json',
    data: form.serialize(),
    beforeSend: function(xhr) {
      xhr.setRequestHeader('Accept', 'text/javascript');
      $('input[type=submit]',form).hide();
      $('.ajax_spinner',form).show();
    },
    success: function(data) {
      if(data.message == 'success') {
        add_prop_to_list(data.html_data);
        //clear_prop_form();
        $('textarea#prop_message').val(data.textarea_message);
        update_captcha(data)
        update_user_summary();        
      } else if(data.message == 'failure') {
        var json = JSON.parse(data.errors);
        var error_messages = "";
        for(var i=0;i < json.length;i++) {
          error_messages += json[i][0] + " " + json[i][1] + "\n";
        }

        alert(error_messages);
      } else if(data.message == 'captcha') {
        update_recaptcha();
        $('form#new_prop input#prop_submit').removeAttr('disabled');
      }
    },
    error: function(request, status, error) {
      alert("Something when wrong with the server and we've been notified about the problem. Please try again in a few moment");
    },
    complete: function(request, status) {
      $('input[type=submit]',form).show();
      $('.ajax_spinner',form).hide();
    }
  });
}

function add_prop_to_list(html_data) {
  $('ul.props').prepend(html_data).find('li:first-child').hide().show('blind');
}

function add_captcha(html_data) {
  $('#button_capcha').prepend(html_data);
}

function clear_prop_form() {
  $('textarea#prop_message').val('');
}

function update_user_summary() {
  var url = document.URL + '/summary';
  $.get(url, function(data){
   $('div.user_stats').replaceWith(data);
  });
}
function update_captcha(data) {
   var url =  'props/captcha_prop';
   $.get(url, function(data){
   $('div.button_capcha_inner').replaceWith(data);
   
  });
  
}
function update_recaptcha(data) {
   var url =  'props/recaptcha_prop';
   $.get(url, function(data){
   $('div.button_capcha_inner').replaceWith(data);

  });

}

function alertuser() {
  alert("Link Successfully copied to clipboard. Now navigate to your email signature and paste.");
}