var reghost = 'forums.familyeducation.com';
var subdomain = window.location.href.split("/")[2].split(".")[0];
if(subdomain.length > 0) {
  switch(subdomain) {
    case 'dev':
    case 'cert':
      reghost = subdomain + '.' + reghost;
      break;
    case 'tveditor':
    case 'recipes':
      break;
    case 'd0':
    case 'd1':
    case 'd2':
    case 'd3':
    case 'd4':
    case 'd5':
      break;
    default:
      reghost = 'dev.' + reghost;
  }
}

$(document).ready(function(){
  $('#login').click(function() {
    showLogin();
    return false;
  });
   $('#login-rcp').click(function() {
    showLogin();
    return false;
  });
    $('#register').click(function(){
    showRegistersubmit();
    return false;
  });
     $('#register-rcp').click(function(){
    showRegistersubmit();
    return false;
  });
  
  $("#registerId").dialog({
    autoOpen: false,
    modal: true,
    height: 625,
    width: 870,
    draggable: false,
    resizable: false,
    zIndex: 10001,
    close: function(){  
      // reload the page 
      location.reload();
    }
  });
  
  $("#loginId").dialog({
    autoOpen: false,
    modal: true,
    height: 285,
    width: 430,
    draggable: false,
    resizable: false,
    zIndex: 10001,
    close: function(){  
      // reload the page 
      location.reload();
    }
  });
 
  $('#logout').click(function(e) {
    $("#logoutwindow").html('<iframe id="logoutwin" style="display:none;" width="0" height="0" frameBorder="0" scrolling="no" /></iframe>');
    try {
      $("#logoutwin").attr("src",pageTracker._getLinkerUrl("http://" + reghost + "/logout")).load(function(){location.reload();});
    }
    catch(exception) {
      $("#logoutwin").attr("src","http://" + reghost + "/logout").load(function(){location.reload();});
    }
    return false;
  });
  
  
   // replace input text when clicked
  $('.foodkeywd').click(function() {
    if (this.value == this.defaultValue) {
      this.value = '';
    }
  });
  $('.foodkeywd').blur(function() {
    if (this.value == '') {
      this.value = this.defaultValue;
    }
  });
  // Autosubmit select box search on select  
  $("select#welcomebrowse").change(function() {
  	if($('.foodkeywd').val()=="Keyword Search") {
				$('.foodkeywd').attr("value","");
			}
    $(this).closest('form').submit();
  });

  $('#recipe-search-form').bind('submit', function(e) {
    var keywords = $('#recipe-search-form > .foodkeywd').val();
    var termname = '';
    try {
      termname = $('#recipe-search-form > #welcomebrowse').val();
      if(termname.length > 0) {
        return true;
      }
    }
    catch(exception) {
      
    }

    if(keywords.length < 3 || keywords == 'Keyword Search'){ 
      $('#recipe-search-form > .error-message').each(function(index, item) {
        $(this).remove();
      });
      $(this).prepend('<div class="error-message">You must provide at least one keyword with three or more characters.</div>');
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
  });
 
 
 // recipe nav
	$("ul.dropdown li").hover(function(){
       $(this).addClass("hover");
		$('div:first',this).css('visibility', 'visible');
		$('ul:first',this).css('visibility', 'visible');
       }, function(){
        $(this).removeClass("hover");
       	$('div:first',this).css('visibility', 'hidden');
		$('ul:first',this).css('visibility', 'hidden');
    });

 
  
  $('#save-recipe').click(function() {
    var throbber = $(this).busy({ 
      position : 'center', 
      hide : true,
      img: '/css/images/busy.gif'
    });
    var member_id = get_member();
    var recipe_id = get_recipe();
    // AJAX the request to the server to use as a proxy to send the request to Drupal
    var params = {
      action: 'save',
      type: 'recipe',
      mid: member_id,
      rid: recipe_id
    };
    
    $.ajax({
      type: 'POST',
      context: throbber,
      url: '/famed/recipes/recipes.php',
      data: params,
      success: function(data, status) {
        var response = eval('(' + data + ')');
        throbber.busy('hide');
        $('#food-stats').replaceWith('<div id="food-stats">' + response.message + '</div>');
        $('#save-recipe').parent().replaceWith('<h4 class="check">Recipe Saved</h4>');
      },
      error: function() {
        throbber.busy('hide');
      }
    });
    return false;
  });
  
  $('#save-ingredients').click(function() {
    var throbber = $(this).busy({ 
      position : 'center', 
      hide : true,
      img: '/css/images/busy.gif'
    }); 
    var member_id = get_member();
    var recipe_id = get_recipe();
    
    // AJAX the request to the server to use as a proxy to send the request to Drupal
    var params = {
      action: 'save',
      type: 'ingredients',
      mid: member_id,
      rid: recipe_id
    };
    $.ajax({
      type: 'POST',
      context: throbber,
      url: '/famed/recipes/recipes.php', 
      data: params,
      success: function(data,success) {
        throbber.busy('hide');
        var response = eval('(' + data + ')');
        $('#food-stats').replaceWith('<div id="food-stats">' + response.message + '</div>');
        $('#save-ingredients').parent().replaceWith('<h4 class="check">Shopping List Saved</h4>');      
      },
      error: function() {
        throbber.busy('hide');
      }
    });
    return false;
  });
  
  $('.save-ingredients').live('click', function() {
    var throbber = $(this).busy({ 
      position : 'center', 
      hide : true,
      img: '/css/images/busy.gif'
    }); 
    var member_id = get_member();
    var recipe_id = $(this).attr('id').substr(7);
    
    // AJAX the request to the server to use as a proxy to send the request to Drupal
    var params = {
      action: 'save',
      type: 'ingredients',
      mid: member_id,
      rid: recipe_id,
      refresh: 1
    };
    $.ajax({
      type: 'POST',
      context: throbber,
      url: '/famed/recipes/recipes.php', 
      data: params,
      success: function(data,success) {
        throbber.busy('hide');
        var response = eval('(' + data + ')');
        $('#food-stats').replaceWith('<div id="food-stats">' + response.message + '</div>');
        $('#shopping-list > div').replaceWith('<div>' + response.content + '<div>');
        //throbber.parent().text('Saved to Shopping List');
        throbber.replaceWith('Saved to Shopping List');
        $('#saved-recipe-items').trigger('update');
      },
      error: function() {
        throbber.busy('hide');
      }
    });
    return false;
  });
  
  try {
    $('#saved-recipe-items').tablesorter();
  }
  catch(Exception) {}
  
  //$('#saved-recipes-wrapper').tabs();

  $('.delete-recipe').live('click', function() {
    var throbber = $(this).busy({ 
      position : 'center', 
      hide : true,
      img: '/css/images/busy.gif'
    });
    var member_id = get_member();
    var recipe_id = $(this).attr('id').substr(7);
    
    // AJAX the request to the server to use as a proxy to send the request to Drupal
    var params = {
      action: 'delete',
      type: 'recipe',
      mid: member_id,
      rid: recipe_id
    };
    $.ajax({
      type: 'POST',
      context: throbber,
      url: '/famed/recipes/recipes.php', 
      data: params, 
      success:  function(data, success) {
        // Update the "Save Recipe" button  
        var response = eval('(' + data + ')');
        if(response.success) {
          //throbber.busy('hide');
          $('#food-stats').replaceWith('<div id="food-stats">' + response.message + '</div>');
          //clicked.parent().parent().fadeTo(400, 0, function () {
          throbber.parent().parent().fadeTo(400, 0, function() {
            $(this).remove();
            $('#saved-recipe-items').trigger('update'); 
          });
        }
        else {
          $('#recipe-messages').addClass('error').html(response.message);
        }
      },
      error: function() {
        throbber.busy('hide');
      }
    });
  });

  $('.delete-ingredients').live('click', function() {
	  var clicked = $(this);
	  var throbber = clicked.busy({ 
      position : 'center', 
      hide : true,
      img: '/css/images/busy.gif'
    });
    var member_id = get_member();
    var recipe_id = $(this).attr('id').substr(7);
    
    // AJAX the request to the server to use as a proxy to send the request to Drupal
    var params = {
      action: 'delete',
      type: 'ingredients',
      mid: member_id,
      rid: recipe_id
    };
    $.ajax({
      type: 'POST',  
      context: throbber,
      url: '/famed/recipes/recipes.php', 
      data: params, 
      success: function(data, success) {
        // Update the "Save Recipe" button  
        var response = eval('(' + data + ')');
        if(response.success) {
          throbber.busy('hide');
          $('#food-stats').replaceWith('<div id="food-stats">' + response.message + '</div>');
          //clicked.parent().parent().fadeTo(400, 0, function () {
          throbber.parent().parent().fadeTo(400, 0, function () {
            $(this).remove();
          });
          var recipe_element =  'recipe-' + throbber.attr('id').substr(7);
          $('#' + recipe_element).parent().html('<a id="' + recipe_element + '" class="delete-recipe" href="javascript:void(0);">delete recipe</a><a id="' + recipe_element + '" href="javascript:void(0);" class="save-ingredients">add to shopping list</a>');
          $('#saved-recipe-items').trigger('update');
          //$('#recipe-messages').addClass('success').html(response.message).fadeIn();
        }
        else {
          $('#recipe-messages').addClass('error').html(response.message);
        }
      },
      error: function() {
        throbber.busy('hide');
      }
    });
  });
	  
  var tabContainers = $('#saved-recipes-wrapper > div');  
  $('#saved-recipes-wrapper ul a').click(function () {
      tabContainers.hide().filter(this.hash).show();
      
      $('#saved-recipes-wrapper ul a').removeClass('selected');
      $(this).addClass('selected');
      return false;
  }).filter(':first').click();
  
  try {
    tabContainers.hide().filter('#'+window.location.hash).show();
  }
  catch(Exception) {}
    
  $('#food-stats > p > a').click(function() {
    try {
      if(window.location.pathname == '/applets/saved_recipes.php') {
        var hash = $(this).attr('href').split('#')[1];
        tabContainers.hide().filter('#'+hash).show();  
        return false;
      }
    }
    catch(Exception) {
      alert(Exception);
    }    
  });
  
  $('#accordion h3:not(:first)').next().hide();
  $('#accordion h3').click(function() {
    $(this).next().toggle('slow');
    return false;
  });
});

function get_member() {
  var data = cookie_value('FeRegU');
  if(data !== false && data !== null) {
    // Due date hasn't been set
    if(data.member_id != undefined) {
      return data.member_id;
    }
  }
  return false;
}

function get_recipe() {
  var urlTokens = (window.location + '').split('/');
  var finalToken = urlTokens[urlTokens.length - 1];
  if(finalToken.length > 1) {
    var recipe_id = finalToken.split('.')[0];
    if(recipe_id > 0) {
      return recipe_id;
    }
  }
  return false;
}

function showRegistersubmit() {
  $("#registerId").html('<iframe id="modalIframeId" width="830" height="570" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" /></iframe>').dialog("open");
  try {
    $('#modalIframeId').attr('src', pageTracker._getLinkerUrl("http://" + reghost + "/user/register/food?rurl="+encodeURI(location.href)));
  }
  catch(Exception) {
    $('#modalIframeId').attr('src', "http://" + reghost + "/user/register/food?rurl="+encodeURI(location.href));
  }
  return false;
}

function showRegister(){
  $("#registerId").html('<iframe id="modalIframeId" width="830" height="570" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" /></iframe>').dialog("open");
  try {
    $("#modalIframeId").attr("src",pageTracker._getLinkerUrl("http://" + reghost + "/user/register/food?rurl="+encodeURI(location.href)));
  }
  catch(Exception) {
    $("#modalIframeId").attr("src","http://" + reghost + "/user/register/food?rurl="+encodeURI(location.href));
  }
  return false;
}

function showRegisterinlogin(){
  $("#registerId").html('<iframe id="modalIframeId" width="830" height="570" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" /></iframe>').dialog("open");
  try {
    $("#modalIframeId").attr("src",pageTracker._getLinkerUrl("http://" + reghost + "/user/register/food?rurl="+encodeURI(location.href)));
  }
  catch(Exception) {
    $("#modalIframeId").attr("src","http://" + reghost + "/user/register/food?rurl="+encodeURI(location.href));
  }
  $('#loginId').dialog('close');
  return false;
}

function showLogin(){
  $("#loginId").html('<iframe id="modalIframeId2" width="395" height="200" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" /></iframe><div id="login-content">Not registered for FamilyEducation.com?  <span id="login-signup"><a href="http://' + reghost + '/user/register/food" onclick="return showRegisterinlogin()">Sign up now.</a></span><div> ').dialog("open");
  try {
    $("#modalIframeId2").attr("src",pageTracker._getLinkerUrl("http://" + reghost + "/members/login?rurl="+encodeURI(location.href)));
  }
  catch(Exception) {
    $("#modalIframeId2").attr("src","http://" + reghost + "/members/login?rurl="+encodeURI(location.href));
  }
  $("#modalIframeId2").load(function(){
    // Check the current hash
    if(window.location.hash.substring(1) == 'done') {
      // Close the dialog
      $('#loginId').dialog('close');
      // Reload page
      window.location = window.location.href.replace( /#.*/, "");
    }
  });
  return false;
}

function dump_response(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;
	
  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";
	
  if(typeof(arr) == 'object') { //Array/Hashes/Objects 
  for(var item in arr) {
    var value = arr[item];
			
      if(typeof(value) == 'object') { //If it is an array,
        dumped_text += level_padding + "'" + item + "' ...\n";
        dumped_text += dump(value,level+1);
      } 
      else {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  } 
  else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}

