var wzModalTrigger = null;
var wzOpenContextMenuID = null;

// Get just the content of the body of an AJAX page. CL adds body stuff automatically.
function getBody(html) {
  var results = html.match(/<body>([\s\S]*)<\/body>/i);
  return results[1];
}

function initUI() {

  initForm();
    
  // Limit length of price
  var maxPriceLength = 10;
  var priceText = "";
  
  var maxPriceWidth = 100; // Max width in pixels
  $(".priceTag span").each(function() {
      var currentFontSize = $(this).css("font-size").substring(0,$(this).css("font-size").indexOf('p'));
      var currentText = $(this).text();
      var currentLength = $(this).text().length;
      
      // size text down
      while(($(this).width() > maxPriceWidth) && (currentFontSize > 10)) {
	currentFontSize--;
	$(this).css("font-size", currentFontSize + "px");
      }
      
      // if it's still too long, cut off the end and replace with ellipsis
      while($(this).width() > maxPriceWidth) {
	currentLength--;
	$(this).text(currentText.substring(0,currentLength) + "...");
      }
    });
  
}

function initForm() {
  $(".text2, .text2 input").addClass("smallCorner-all");
  $(".text2 label").addClass("smallCorner-bottom");
  $(".button").addClass("corner-all");
  
  $(".text2 input")
    .focus(function() {
	$(this).parent().addClass("currentField");
      })
    .blur(function() {
	$(this).parent().removeClass("currentField");
      });
}

function initInvites() {
  var inviteRow = $(".inviteForm tbody").html();
  var n = 1;
  
  function incrementFields() {
    $(".inviteField").each( function() {
	var name = $(this).attr("name");
	$(this)
	  .attr("name", name + "_" + n)
	  .removeClass("inviteField");
      });
    n = n+1;
  }
  
  incrementFields();

  $(".inviteForm a.addRow").live("click", function () {
      
      $(".inviteForm tbody")
	.append(inviteRow);
      incrementFields();
      $(this)
	.html("remove")
	.removeClass("addRow")
	.addClass("removeRow");

      $(this)
	.closest("tr")
	.next("tr")
	.find("input:first")
	.focus()
	.parent()
	.addClass("currentField");
      
      initForm();
      return false;
    });

  $(".inviteForm a.removeRow").live("click", function () {
      $(this).parent().parent().remove();
      return false;
    });
}

function initAjaxForm() {
  $(".results").hide();

  // Initialize the AJAX form submission
  
  $(".ajaxForm").ajaxForm({
    success: function(html){
	$(".results")
	  .hide()
	  .html(html)
	  .slideDown("fast");

	continueIfValid();
      }
    });
}

function initIntraModalAjaxForm() {
  $(".results").hide();

  // Initialize the AJAX form submission
  
  $(".intraModalAjaxForm").ajaxForm({
    success: function(html){
	$(".modalContent")
	  .html(getBody(html));
	if ($(".results").length)
	  $(".results").slideDown();
      }
    });
}

function initTabbedEditor() {
  $("ul.edit-tabs").tabs("div.edit-panes > div.pane", {
    effect:'fade'
	});

  initAjaxForm();
}

function initOverlay() {
  var modalContent, url;


  modalContent = $(".modalContent");
  modalContent.html("<div style='text-align:center'><img src='i/loading.gif' alt='Loading...' /></div>");

  // Load the linked page into the modal content
  url = wzModalTrigger.attr("href");
  if (url == null)
    url = wzModalTrigger.attr("action");
  modalContent.load(url,function(){
      initUI();
    });

  $(".results").hide();
}

function initLogin() {
  
  $(".loginOptions").tabs("div.login-panes > div.pane" , {
    effect: 'fade'
	});	    
  
  // Check to see if the user clicked the signup link
  if(wzModalTrigger && wzModalTrigger.attr("id") == "signup") {
    var tabsApi = $(".loginOptions").tabs();
    tabsApi.click(2);
    $("input#cl_account_new_1")
      .focus()
      .parent().addClass("currentField");
  } else {
    $("input#cl_account_1")
      .focus()
      .parent().addClass("currentField");
  };

  // Initialize the AJAX form submission
  
  $("#i_loginForm").ajaxForm({
    success: function(html){
	$(".results")
	  .hide()
	  .html(html)
	  .slideDown("fast");
	$("#cl_password_1").val("").focus();

	continueIfValid();
      }
    });
  
  $("#i_signupForm").ajaxForm({
    success: function(html){
	$("#i_signupResults")
	  .hide()
	  .html(html)
	  .slideDown("fast");

      	continueIfValid();}
    });
}

function initValidate() {
  $("#i_validateForm").ajaxForm({
    success: function(html){
	$(".results")
	  .hide()
	  .html(html)
	  .slideDown("fast");

	continueIfValid();}
    });
}

function continueIfValid() {
  if ($("#validURL").length > 0) {
    $("#validURL").hide()
      .parent().parent().next("form").slideUp("fast");

    if ((wzModalTrigger != null) && (wzModalTrigger.attr("ajaxreturnto") > "")) {
      $(".modalContent").load(wzModalTrigger.attr("ajaxreturnto"), wzModalTrigger = null);
    }
    else {
      if ((wzModalTrigger != null) && (wzModalTrigger.attr("action"))) {
	var value;
	
	wzModalTrigger
	  .attr("action", wzModalTrigger.attr("returnto"))
	  .removeAttr("returnto");
	value = $("[name=body]", wzModalTrigger).val();
	value = value.replace(/^\s+|\s+$/g,"");
	if (value > "")
	  wzModalTrigger.submit();
	else
	  window.location.reload();
      }
      else {
	if ((wzModalTrigger != null) && (wzModalTrigger.attr("returnto") != ""))
	  $("#validURL").attr("href", wzModalTrigger.attr("returnto"));
	var url = $("#validURL").attr("href");
	window.location.href = url;
      }
    }
  }  
}

function initNews() {
  $(".newsWrapper")
    setTimeout( function() {
	$(".newsWrapper").slideDown("slow");
      }, 2000);

  $(".newsWrapper a.closeNews").live("click", function() {
      $(this).parent().slideUp("slow");
    })
}

function installOverlay(obj) {
  obj.overlay({
    speed: 100,
    expose: {
      color: '#222',
	  loadSpeed: 50,
	  opacity: 0.8
	  },
	  
	closeOnClick: false,
	  
	onBeforeLoad: function() {
	// Set the modal trigger state to the ID of the trigger link
	wzModalTrigger = this.getTrigger();
	if (!wzModalTrigger.attr("href"))
	  wzModalTrigger = wzModalTrigger.closest("form");
	initOverlay()
	  },
	  
	onLoad: initUI()
	});
}

function closeContextMenus() {
  // Close any open menu
  if ($(".contextMenuSelected").length) {
    $(".contextMenuSelected")
      .removeClass("contextMenuSelected")
      .addClass("contextMenu")
      .next("ul")
      .fadeOut(50);
  }
}

function initChildManager() {
  var numSelectedFamilies = 0;
  var numSelectedManagers = 0;

  $(".familyListing .familyCheckbox").each(function() {
      if ($(this).attr("checked"))
	numSelectedFamilies++;
    });

  $(".familyListing .familyCheckbox").each(function() {
      if ($(this).attr("checked"))
	$(this).closest("td").next("td").find(".allowSwitchTo").show();
    });

  $(".allowSwitchTo input:checkbox").each(function() {
      if ($(this).attr("checked"))
	numSelectedManagers++;
    });

  $(".allowSwitchTo input:checkbox").change(function() {
      if (!($(this).attr("checked"))) {
	numSelectedManagers--;
	if ((numSelectedManagers == 0) && ($(this).attr("truechild") == 1)) { 
	  $(this).attr("checked", "checked");
	  numSelectedManagers++;
	}
      }
      else numSelectedManagers++;
    });
  
  $(".familyListing .familyCheckbox").change(function() {
      var allowSwitchTo = $(this).closest("td").next("td").find(".allowSwitchTo").find("input:checkbox");
      if ($(this).attr("checked")) {
	numSelectedFamilies++;
	allowSwitchTo.closest(".allowSwitchTo").fadeIn();
	if (allowSwitchTo.attr("checked")) numSelectedManagers++;
      }
      else {
	numSelectedFamilies--;
	if (numSelectedFamilies == 0) {
	  $(this).attr("checked", "checked");
	  numSelectedFamilies++;
	}
	else {
	  if ((numSelectedManagers > 1) || !(allowSwitchTo.attr("checked"))) {
	    allowSwitchTo.closest(".allowSwitchTo").fadeOut(function() {
		if (allowSwitchTo.attr("checked")) {
		  numSelectedManagers--;
		}
	      });
	  }
	  else {
	    $(this).attr("checked", "checked");
	    numSelectedFamilies++;
	  }
	}
      }
    });
}

// Embed code for public profiles
function initEmbed() {
  $("#embed").val('<iframe id="wz_embed" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" style="overflow:visible; width:100%; margin:25px 0; border:solid 1px #A7B7B6" height="600" src="http://wishzilla.com' + $("#embedURL").attr("href") + '"></iframe>');
  
  if ( $("#public").attr("checked") ) $(".embedCode").show();
  else $(".embedCode").hide();
  
  $("input[name=public]").live("click", function() {
      if ($(this).val() == 1) $(".embedCode").slideDown("fast");
      else $(".embedCode").slideUp("fast");
    });

  $("#embed")
    .focus(function() {
	$(this).select();
      })
    .click(function() {
	$(this).select();
      });
}


$(document).ready(function() {
    // Get the name if the URL contains it
    var thisAnchor = window.location.hash;
    if(thisAnchor) {
      thisAnchor = thisAnchor.substring(1,thisAnchor.length);
      // Expand and highlight the wish targeted by the named anchor
      $(".aHead[name=" + thisAnchor + "]").each(function() {
	  $(this).addClass("aHeadCurrent")
	    .removeClass("aHead")
	    .nextAll(".aBody").show();
	  $(this).closest(".aWrap")
	    .addClass("newSelected");
	});
    }

    initUI();

    $(".intraModal").live("click", function() {
	var url = $(this).attr("href");
	$(".modalContent")
	  .load(url,"",function() {
	      initUI();
	      $(".ajaxForm").ajaxForm({
		success: function(html){
		    $(".results")
		      .hide()
		      .html(html)
		      .slideDown("fast");
		    continueIfValid();
		  }
		});
	    });
	return false;
      });

    $("img.masked").each(function() {
	$(this)
	  .after("<img class='overlayImage png_bg' src='theme/current/i/mask.png' />");
	var titleText = $(this).attr("title");
	$(this).next(".overlayImage").attr("title", titleText);
      });

    $("a.[rel='#prompt'], input.loginPrompt").each(function() {
	installOverlay($(this));
      });
    
    // Initialize Tabs
    $(".loginOptions").tabs("div.login-panes > div.pane" , {
      effect: 'fade'
	  });	        

    if ($("ul.list-tabs").length > 0) {
      // Initialize list tabs
      var listTabs = $("ul.list-tabs").tabs("div.list-panes > div.pane" , {
	effect: 'fade',
	    api: true,
	    onBeforeClick: function() {
	    closeContextMenus();
	  },
	    onClick: function() {
	    $.cookie("listTabsIndex", this.getIndex());
	    initUI();
	  }
	});
      
      // Open the current tab
      if($.cookie("groupTabsIndex") != null) {
	listTabs.click(parseInt($.cookie("listTabsIndex")));
	initUI();
      }
    }

    if ($("ul.group-tabs").length > 0) {
      var groupTabs = $("ul.group-tabs").tabs("div.group-panes > div.pane" , {
	effect: 'fade',
	    api: true,
	    onClick: function(){
	    $.cookie("groupTabsIndex", this.getIndex());
	  }
	});

      // Open the current tab
      if($.cookie("groupTabsIndex") != null) {
	groupTabs.click(parseInt($.cookie("groupTabsIndex")));
      }

      // Open the current tab
      if($.cookie("groupTabsIndex") != null) {
	groupTabs.click(parseInt($.cookie("groupTabsIndex")));
      }
    }
      
    // Simple accordions    
    $(".aHead").live("click", function() {
	$(this).parent().parent().find(".aHeadCurrent")
	  .addClass("aHead")
	  .removeClass("aHeadCurrent")
	  .siblings(".aBody")
	  .slideUp("fast");
	$(this)
	  .addClass("aHeadCurrent")
	  .removeClass("aHead")
	  .siblings(".aBody")
	  .slideDown("fast");
	if ($(this).attr("id").length > 0) {
	  $.cookie("currentFamily", $(this).attr("id"));
	}
	return(false);
      });

    // Open the accordion based on the family cookie
    if(($.cookie("currentFamily") != "") && ($("ul.group-tabs").length > 0)) {
      $("#" + $.cookie("currentFamily"))
	.addClass("aHeadCurrent")
	.removeClass("aHead")
	.siblings(".aBody")
	.show();
    }

    // Open the first family accordion if there's no cookie and only one family
    if(($.cookie("currentFamily") == null) && ($("#families .aFwrap").length == 1)) {
      $("#families .aHead:first")
	.addClass("aHeadCurrent")
	.removeClass("aHead")
	.siblings(".aBody")
	.show();
    }

    // Select the family tab if there are families but no friends
    if(($(".firstInviteBt").length) && ($("#families .aFwrap").length)) {
      groupTabs.click(1);
    }
    
    $(".aHeadCurrent").live("click", function() {
	$(this)
	  .addClass("aHead")
	  .removeClass("aHeadCurrent")
	  .siblings(".aBody")
	  .slideUp("fast");
	$.cookie("currentFamily", null);	
	return(false);
      });

    $(".hoverMenu").tooltip({
      position:"bottom right",
	  bounce:"true",
	  direction:"right",
	  slideOffset:10,
	  offset:[-30,-50]
      });
    
    // Handle showing AJAX content immediately after a link

    $(".ajaxAfter").live("click", function() {
	var url = $(this).attr("href");
	$(this)
	  .after("<div class='ajaxAfterContent' />")
	  .removeClass("ajaxAfter")
	  .addClass("ajaxAfterLoaded");
	$(".ajaxAfterContent")
	  .hide()
	  .load(url)
	  .slideDown("fast");

	return false;
      });

    $(".ajaxAfterLoaded").live("click", function() {
	$(this)
	  .removeClass("ajaxAfterLoaded")
	  .addClass("ajaxAfter");
	$(".ajaxAfterContent")
	  .slideUp("fast")
	  .remove();

	return false;
      });

    // Home page log in form
    $("#loginForm").ajaxForm({
      success: function(html){
	  $("#loginResults")
	    .hide()
	    .html(html)
	    .slideDown("fast");
	  $("#cl_password").val("").focus();

	  continueIfValid();
	}
      });

    // Sidebar signup form
    $("#signupForm").ajaxForm({
      success: function(html){
	  $("#signupResults")
	    .hide()
	    .html(html)
	    .slideDown("fast");

	  continueIfValid();
	}
      });

    // Gift management context menu

    $(".contextMenu").live("click", function() {
	if ($(this).attr("id") != wzOpenContextMenuID) {
	  var menuWidth = $(this).parent().width() + 1;
	  var menuHeight = $(this).parent().height();
	  if ($(this).attr("id") != "lockMenu_switch")
	    $(this).next("ul").css("left", menuWidth + "px");
	  else 
	    $(this).next("ul")
	      .css("top", menuHeight + "px")
	      .css("right", "0");
	  $(this)
	    .addClass("contextMenuSelected")
	    .removeClass("contextMenu")
	    .next("ul")
	    .fadeIn(150);
	}
	return false;
      });

    // Watch the click event to manage the gift context menu
    $("body").click(function() {
	if ($(".contextMenuSelected").length)
	  wzOpenContextMenuID = $(".contextMenuSelected:first").attr("id");
	else
	  wzOpenContextMenuID = null;
	closeContextMenus();
      });
    
    // Index page large buttons
    // set opacity to 0 on page load
    $(".indexBt-content a span")
      .css("opacity","0")
      .show();
    
    // on mouse over
    $(".indexBt-content a span").hover(function () {
	// animate opacity to full
	$(this).stop().animate({
	  opacity: 1
	      }, 350);
      },
      // on mouse out
      function () {
	// animate opacity to nill
	$(this).stop().animate({
	  opacity: 0
	      }, 200);
      });
    
    // Select all
    $("A[href='#select_all']").click( function() {
	$("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true);
	return false;
      });
    
    // Select none
    $("A[href='#select_none']").click( function() {
	$("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', false);
	return false;
      });
    
    // Invert selection
    $("A[href='#invert_selection']").click( function() {
	$("#" + $(this).attr('rel') + " INPUT[type='checkbox']").each( function() {
	    $(this).attr('checked', !$(this).attr('checked'));
	  });
	return false;
      }); 
    
    // Comment management
    $(".commentReply").live("click",function() {
	var replyButton = $(this);
	var commentWrapper = $(this).closest(".comment-wrapLeft");
	$.ajax({
	  url: $(this).attr("href"),
	      success: function(ajaxEdit) {
	      replyButton.hide();
	      replyButton.parent().after(getBody(ajaxEdit));
	      commentWrapper.find(".replyTo:first").slideDown("fast",function(){
		  var theForm;

		  theForm = commentWrapper.find("form:first");
		  if (!theForm.attr("notLoggedIn"))
		    theForm.ajaxForm({
		      success: function(ajaxEditResult){
			  // Place results into a hidden container to check for error state
			  commentWrapper.find(".replyTo:first .commentAjaxResult").html(getBody(ajaxEditResult));
			  commentWrapper.find(".replyTo:first .commentError")
			    .slideUp("fast");
			  
			  if(commentWrapper.find(".replyTo:first .commentAjaxResult .error").length){
			    // Show the error
			    commentWrapper.find(".replyTo:first .commentError")
			      .html(getBody(ajaxEditResult))
			      .slideDown();
			  } else {
			    // Remove the editor and place the comment
			    commentWrapper.find(".replyTo:first")
			      .slideUp(function(){
				  replyButton.parent().after(getBody(ajaxEditResult));
				  commentWrapper.find(".ajaxComment")
				    .slideDown()
				    .removeClass("ajaxComment");
				  commentWrapper.find(".replyTo:first").remove();
				})
			      replyButton.fadeIn();
			  }
			}
		      })
		      .find("textarea").focus();
		  else
		    $("input.loginPrompt").each(function() {
			installOverlay($(this));
		      });
		});
	    }
	  });
	return false;
      });

    $(".toggleComment").toggle(function(){
	$(this).removeClass("hideComment");
	$(this).addClass("showComment").fadeIn("slow");
      }, function () {
	$(this).removeClass("showComment");
	$(this).addClass("hideComment").fadeIn("slow");
      });

    $(".toggleComment").click(function() {
	$(this).parent().next(".commentBody-wrap").slideToggle();
      });
    
    $(".cancelComment").live("click", function() {
	var parentComment = $(this).closest(".comment-wrap");
	$(".replyTo:first",parentComment).slideUp(function(){$(this).remove()});
	$(".commentReply:first",parentComment).fadeIn();
	return false;
      });

    $(".newCommentForm").ajaxForm({
      success: function(newComment){
	  $(".newComment .commentError").slideUp("fast");
	  $(".newComment .commentAjaxResult").html(getBody(newComment));
	  if($(".newComment .commentAjaxResult .error").length){
	    $(".newComment .commentError")
	      .html(getBody(newComment))
	      .slideDown("fast");
	  } else {
	    $(".newComment").before(getBody(newComment));
	    $(".ajaxComment")
	      .slideDown("fast",function(){
		  $(".ajaxComment").removeClass("ajaxComment");
		})
	      }
	},
	  clearForm: true
	  });
    
    // AJAX comment voting
    $(".commentVotes-wrap a.commentVote").live("click",function(){
	var commentVotes = $(this).parent();
	$.ajax({
	  url: $(this).attr("href"),
	  cache: false,
	      success: function(voteBlock){
	      commentVotes.fadeTo(50,0.05,function(){
		  commentVotes.html(getBody(voteBlock));
		  commentVotes.fadeTo(400,1);
		});
	    }
	  });
	return false;
      });
    
    // User switching
    $(".enableFastUser").live("click", function() {
	if ($(this).attr("checked")) {
	  $(".availableFamilies input:checkbox").attr("disabled", "");
	  $(".availableFamilies").slideDown();
	}
	else {
	  $(".availableFamilies").slideUp();
	  $(".availableFamilies input:checkbox").attr("disabled", "disabled");
	}
      });
    
    // Prevent users from unchecking if there's only one family and it's a true child account
    $(".availableFamilies input:checkbox").live("click", function() {
	var numChecked = 0;
	var thisCheckbox = $(this);

	// The .enableFastUserDisabled class only exists child accounts
	if($(".enableFastUserDisabled").length) {
	  if ($(".availableFamilies label").length == 1)
	    $(this).attr("checked", "checked");
	  
	  // Prevent users from unchecking if it's the last family checked
	  $(".availableFamilies label").each(function() {
	      if ($("input:checkbox", this).attr("checked"))
		numChecked++;
	    });
	  
	  if (numChecked == 0) thisCheckbox.attr("checked", "checked");
	}
      });

    // Secret Santa selections
    $(".santaParticipants input:checkbox").live("click", function() {
	if($(this).attr("checked"))
	  $(this).closest(".familyListing").css("background-color", "#fcefd0");
	else
	  $(this).closest(".familyListing").css("background-color", "#efefef");
      });
    
    $('.imageSorter').sortable({
      update: function(event, ui) {
	  $('#' + $(this).attr('id') + 'Order').attr('value', $(this).sortable('toArray', {'attribute' : 'position'}));
	},
	  placeholder: 'ui-state-highlight',
	  forcePlaceholderSize: 'true'
	  });

  });


