$(document).ready(function () 
{

  bindQuestionLinks();
  bindContactForm(); 
  checkPrefillQuestion();

  $('input#searchText').bind('keyup', function(e) {
    if ( e.keyCode == 13 )
    {
      $('#searchSubmit').trigger('click');
    }
  });

  $('#searchSubmit').click( function(){
    var searchString = $('#searchText').val();
    if ( searchString.replace(/^\s+|\s+$/g,"").length > 0 )
    {
      $.ajax({
        url:'/ajax/search',
        type:'post',
        data:{searchString:searchString},
        success: function ( markup )
        {
           $('a.categoryTextLink').removeClass( 'bold' );
           $('div#categoryResult').hide();
           $('div#searchResult').html( markup ).show();
           bindQuestionLinks();
           bindContactForm();
        }
      });
    }

  });

});

function checkPrefillQuestion ( )
{

  question = parseInt ( $('#prefillQuestionId').html( ) );
  if ( parseInt ( question ) ) 
  {
    showHideQuestion( 'question', question );
    onload = function(){window.location.href = "#question" + question;}
  }
  
}

function contactForm( autoName, autoEmail, autoUserid, vipUser )
{
  if ( vipUser )
  {
    form = "<div id='contactForm' class='vipForm'><div class='field'><label>Full Name: </label><div class='fullname'><span id='name'>" + autoName  + "</span></div></div><div class='field'><label>Subject: </label><select id='subject' name='subject'><option name='subject' value='VIP Membership Questions'>VIP Membership Questions</option><option name='subject' value='Lunch Money Issues'>Lunch Money Issues</option><option name='subject' value='Profile & Site Feature Questions'>Profile & Site Feature Questions</option><option name='subject' value='Suggestions'>Suggestions</option><option name='subject' value='Other'>Other</option></select></div><div class='field hide' id='subjectField'><label></label><input type='text' name='otherSubject' id='otherSubjectInput' value='Type your subject here...'/></div><div class='field'><label>Message: </label><textarea id='message'></textarea></div><div class='center'>A myYearbook Member Services representative will get back to you within 24 hours.</div><div class='submit'><div id='error' class='hide'/><input type='hidden' name='type' value='vip' /><img src='" + IMAGE_URL + "btn_submit.gif' id='submitContactForm' class='vip'/></div></div>";
  }
  else 
  {
    form = "<div id='contactForm'><div id='contactHeader'>Type of Inquiry:</div><div class='radio'><input type='radio' name='type' value='general' id='general'><label for='general'>General Feedback</label></div><div class='radio'><input type='radio' name='type' value='bugs' id='bugs'><label for='bugs'>Report Bugs & Technical Errors</label></div><div class='field'><label>Full Name: </label>";
    if ( autoUserid ) 
    {
      form += "<span id='name'>" + autoName + "</span>";
    } else {
      form += "<input id='name' type='text' />";
    }
    form += "</div><div class='field'><label>Email: </label>";
    if ( autoUserid ) 
    {
      form += "<span id='email'>" + autoEmail + "</span>";
    } else {
      form += "<input id='email' type='text' />";
    }
    form += "</div><div class='field'><label>Subject: </label><input id='subject' type='text' /></div><div class='field'><label>Message: </label><textarea id='message'></textarea></div><div class='submit'><div id='error'></div><img id='submitContactForm' src='" + IMAGE_URL + "btn_submit.gif'></div><div id='reportAbuseBox'><span class='reportAbuse'>Report Abuse:</span> If you need to report inappropriate content or behavior you have observed on myYearbook, do not submit feedback here.  Instead, click the <img src='" + IMAGE_URL + "images/report_abuse_header_icon.gif'> icon on the top right-hand corner of the page containing the inappropriate material.</div></div>";
  }
  return form;
}

function successContactForm( type )
{
  if ( type == 'vip' )
  {
    return "<div id='vipSuccess'><div class='vipSuccessThanks'>Thank you for your inquiry.</div><div class='vipSuccessMessage'>A myYearbook Member Services Representative will get back to you shortly.</div><div class='vipSuccessClose'><a href='#' onclick='$(\".dragon.vipSupportForm\").slayDragon( null, true );return false;'><img src='" + IMAGE_URL + "btn_close.gif' /></a></div></div>";
  }
  else
  {
    return "<div id='contactSuccess'><div id='successHeader'>Your feedback has been submitted to myYearbook Member Services.</div>";
  }
}

function bindQuestionLinks( )
{

  $('a.questionLink').unbind().bind('click', function()
  {
  
    var questionType = $(this).parents('li').attr('rel');
    var question = $(this).parents('li').attr('id').replace( questionType, '');

    showHideQuestion( questionType, question );
  
  });
    
}

function showHideQuestion( type, question )
{

  if ( question && parseInt ( question ) ) 
  {
    
    questionBox = '#' + type + question;
    var answer = $( questionBox ).find(".answerText");
    if ( $(answer).css('display') == 'none' )
    {    
      $.ajax( {
        url:'/ajax/viewQuestion/',
        type:'post',
        data:{question:question}
      });
      $(answer).show();
    } else {
      $(answer).hide();
    }
    return false;
  }
  
}

function bindContactForm()
{

  $('.contact').unbind('click');
  $('.contact').bind('click' , function(e)
  {
    autoName = jQuery.trim ( $('#userName').attr('class') );
    autoEmail = jQuery.trim ( $('#userEmail').attr('class') );
    autoUserid = $('#userid').attr('class');

    var formTitle = 'Submit Feedback';    
    if ( $(this).hasClass('vip') )
    { 
      var vipUser = true;
      var formTitle = 'VIP Support Request Form';
    }

    $('<div />').appendTo('body')
      .dragonDrop({
        type:'window',
        title: formTitle,
        content: contactForm( autoName, autoEmail, autoUserid, vipUser ),
        displayClass: 'dragonWhite vipSupportForm',
        enableMinMax: false,
        width:420,
        curtain: true,
        draggable: false,
        enableClose: true
      }).find('select').show();

      $('select#subject').change( function() {
        if ( $(this).val() == 'Other')
        {
          $('#subjectField').show();
        }
        else
        {
          $('#subjectField').hide();
          $('#otherSubjectInput').val('Type your subject here...');
        }
      });

      $('#otherSubjectInput').focus(function(){
      if ( $(this).val() == 'Type your subject here...' ) {
        $(this).val(''); 
      }
    });

    $('#submitContactForm').bind('click', function() 
    { 
      helptype = $("#contactForm input[name='type']:checked").val(); 
      if ( !helptype )
      {
        helptype = $("#contactForm input[name='type']").val(); 
      }
      if ( autoUserid )
      {
        helpname = autoName;
        helpemail = autoEmail; 
      } else {
        helpname = $('#contactForm').find('#name').val();
        helpemail = $('#contactForm').find('#email').val();
      }
    
      helpsubject = $('#contactForm').find('#subject').val();
      if ( helpsubject == 'Other' )
      {
        helpsubject = $('#contactForm').find('#otherSubjectInput').val();
      }
      helpmessage = $('#contactForm').find('#message').val();
      screenres = screen.width + 'x' + screen.height;


      var errorMessage = '';
      //Let's check the form before sending it (subject, message)
      if ( helpsubject.length < 1 || helpsubject == 'Type your subject here...' )
      {
        errorMessage += 'Please input or select a valid subject.<br/>'
      }

      if ( helpmessage.length < 1 ) 
      {
        errorMessage += 'Please input a message.<br/>';
      }

      if ( errorMessage.length > 0 )
      {
        $('#error').html( errorMessage );
        $('#error').show();
      }
      else
      {
        $.ajax( {
          url:'/ajax/contact',
          type:'post',
          dataType:'json',
          data:{type:helptype,name:helpname,email:helpemail,subject:helpsubject,message:helpmessage,userid:autoUserid,screenres:screenres},
          success: function ( data )
          {
            if ( data.error )
            {
              $('#error').html( data.error );
              $('#error').show();
            } else {
              $('#contactForm').html ( successContactForm( data.type ) );
            }
          }
        });         
      }
    });
    return false;
  });

}
