var selectedProductCol = 0;
var selectedReceiverGroup = 0;
var currentAction = "start";
var lastAction = null;
function trackCall(obj){
	for (var i in obj) {
		s[i] = obj[i];
	}
	s.server="MHS";
	s.linkInternalFilters="javascript:,subscribe.hearstmags.com,www.myholidayshopper.com"
	var s_code=s.t();if(s_code)document.write(s_code);
}
$(document).ready(function() {
	var endIndex = location.href.indexOf("com");
	var finalwebroot = location.href.substr(0,endIndex+4);
	if(endIndex>0){
		webroot = finalwebroot;
	}
	
	initWidgetInteraction();
});


function initWidgetInteraction() {
	if(currentAction == "logout" && window.location.href.indexOf("/users/") > -1)
		window.location = webroot + "finder";
	
	// Init print icon
	$("a.icon_print").click(function(){	
		showPrintBubble(this);
		return false;
	});

	// Init "Print all lists" in print-bubble
	$("a.print_all_lists").click(function(){
		//hidePrintBubble();
		window.location = webroot + "users/printList";
		return false;
	});

	// Init "Print [name]'s lists" in print-bubble
	$("a.print_selected_lists").click(function(){
		//hidePrintBubble();
		var current_id = $("div.widget_item.selected").attr("id").split("_")[1];
		window.location = webroot + "users/printList/" + current_id;
		return false;
	});

	// Init fake radio-buttons
	$("a.radio").click(function(){
		showRadioBubble(this);
		return false;
	});

	// Initing the button for skipping forward through the product list
	$("a.next_btn2").click(function(){
		showNextProductCol();
		return false;
	});

	// Initing the button for skipping backwards through the product list
	$("a.prev_btn2").click(function(){
		showPrevProductCol();
		return false;
	});

	// Set the width of the div containg the products based on the number of products.
	$("div.widget_clipper").css("width", $(".product_col").length * 162 + "px");
	
	// Making the names in the receiver list clickable
	$("div.widget_item span").click(function(){
		selectReceiver(this);
	});

	// Init the link that opens the Add Recipient Box
	$("a.add_a_recipient").click(function(){
		showAddRecipientBox();
		return false;
	});
	
	// Init the "Cancel" btn in the Add Recipient Box
	$("a.cancel_add_recipient").click(function(){
		hideAddRecipientBox();
		return false;
	});

	// Initing the button for skipping forward through the recipient list
	$("a.next_btn").click(function(){
		nextRecipentGroup();
		return false;
	});

	// Initing the button for skipping backwards through the recipient list
	$("a.prev_btn").click(function(){
		prevRecipentGroup();
		return false;
	});

	$("a.icon_send").click(function(){
		updateWidget("email");
		return false;
	});
	
	// Initing the "Edit" button in the recipient list
	$("div.widget_item span a").click(function(){
		window.location = webroot + "users/index/" + $(this).parent().parent("div.widget_item").attr("id").split("_")[1];
		return false;
	});

	// Init the Register("Create Now") btn
	$("a#sign_up").click(function(){
		updateWidget("register");
		return false
	});

	// Init the Login here link
	$("a#login").click(function(){
		//alert('yo');
		updateWidget("login");
		return false;
	});

	// Init cancel buttons (used on multiple pages)
	$("a#cancel").click(function(){
		if(null != lastAction)
			updateWidget(lastAction);

		return false;
	});

	// Init the Done button on the login screen
	$("a#login2").click(function(){
		//alert('yo');
		if($("input#user_name").val() == "" && $("input#password").val() == "") {
			
			$("input").css("border-color", "#fff");
			alert("Please enter Email and Password");
		} else {
			
			var data = {user_name : $("input#user_name").val(), password : $("input#password").val()};
			updateWidget("login", data);
		}

		return false;
	});

	$("a#logout").click(function(){
		updateWidget("logout");
		return false;
	});

	$("a#edit_profile").click(function(){
		updateWidget("profile");
		return false;
	});
	
	$("a#register_post").click(function(){
		var alertMsg = validateForm();

		if(alertMsg.length > 0)
			alert(alertMsg);
		else
			registerIfUsernameAvailable();
		
		return false;
	});

	$("#send_email").click(function(){
		var alertMsg = validateForm();

		if(alertMsg.length > 0)
			alert(alertMsg);
		else {
			var data = {
						recipient : $("select#recipient").val(),
						first_name : $("input#first_name").val(),
						last_name : $("input#last_name").val(),
						email : $("input#email").val(),
						message : $("textarea#message").val()
						};

			updateWidget("sendList", data);
		}
		return false;
	});

	$("#send_email2").click(function(){
		var alertMsg = validateForm();

		if(alertMsg.length > 0)
			alert(alertMsg);
		else {
			var data = {
						recipient : $("select#recipient").val(),
						first_name : $("input#first_name").val(),
						last_name : $("input#last_name").val(),
						email : $("input#email").val(),
						message : $("textarea#message").val()
						};

			$.post(webroot + "/widget/widgets/sendList", data, function(){
				console.debug("message", "tjohoo!");
				
				$("#email_box").hide();
			})
			//updateWidget("sendList", data);
		}
		return false;
	});
	
	$("#back_to_giftlist").click(function(){
		updateWidget("giftlist");
		return false;
	});
	
	$("#back_to_giftlist2").click(function(){
		updateWidget("giftlist");
		return false;
	});
	
	
	$("#save_profile").click(function(){
		var alertMsg = validateForm();

		if(alertMsg.length > 0)
			alert(alertMsg);
		else {
			var data = {user_name : $("input#user_name").val()};
			$.post(webroot + "/widget/widgets/checkUsernameAvailable/1", data, function(data, textStatus) {
				if(data.split("<")[0] == 1) {
					data = {
							user_name : $("input#user_name").val(),
							password : $("input#password").val(),
							first_name : $("input#first_name").val(),
							last_name : $("input#last_name").val(),
							giftideaname : $("input#giftideaname").val(),
							relation : $("select#relation").val()
					};

					updateWidget("saveProfile", data);
				} else {
					$("input#user_name").focus().css("border-color", "#f00");
					alert("The new Email you have selected is already in use by someone else");
				}
			});
		}	
		
		return false;	
	});

	$("#save_profile2").click(function(){
		var alertMsg2 = validateForm2();

		if(alertMsg2.length > 0)
			alert(alertMsg2);
		else {
			var data = {user_name : $("input#user_name").val()};
			$.post(webroot + "/widget/widgets/checkUsernameAvailable/1", data, function(data, textStatus) {
				if(data.split("<")[0] == 1) {
					data = {
							user_name : $("input#user_name").val(),
							password : $("input#password").val(),
							first_name : $("input#first_name2").val(),
							last_name : $("input#last_name2").val(),
							giftideaname : $("input#giftideaname").val(),
							relation : $("select#relation").val()
					};

					updateWidget("saveProfile", data);
				} else {
					$("input#user_name").focus().css("border-color", "#f00");
					alert("The new Email you have selected is already in use by someone else");
				}
			});
		}	
		
		return false;	
	});

	// If the login-username is set on render it means the user has been trying to login but with the wrong login/password
	
	if($("div.widget.start input#user_name").css("borderColor")) {
		if(!$.browser.msie){
			alert("No user was found with Email/Password that you've provided. Please try again!")
		}
	}

	$("div#add_recipient a.done_add_recipient").click(function() {
		if($("div#add_recipient input#new_name").val() != "") {
			var data = {name : $("div#add_recipient input#new_name").val(), relation : $("div#add_recipient select#new_relation").val()};	
			updateWidget("addList", data);
		} else {
			alert("Please enter Name");
			$("div#add_recipient input#new_name").focus().css("border-color", "#f00");
		}
		return false;
	});

	$("a#email_to_friend").click(function(){
		var newLeft = ($(window).width() / 2) - 200;
		$("#email_box").show();
		$("#email_box").css("left", newLeft);
		return false;
	});

	$("a#cancel_send").click(function(){
		$("#email_box").hide();
		return false;
	});

	updateProductCols();
	updateReceivers();
}

function validateForm() {
	alertMsg = "";

	// Restoring the border color on all elements in case there has been an earlier validation
	$("input").css("border-color", "#a2e0fa");

	if($("textarea#message").val() == "") {
		alertMsg = "- Please write a Message\n" + alertMsg;
		$("textarea#message").css("border-color", "#f00");
	}

	if($("input#email").val() == "") {
		alertMsg = "- Please enter Email\n" + alertMsg;
		$("input#email").focus().css("border-color", "#f00");
	} else if($("input#email").val()) {
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test($("input#email").val()))
			alertMsg = "- Please enter valid Email\n" + alertMsg;

		$("input#email").focus().css("border-color", "#f00");
	}


	if($("select#relation").val() == "") {
		alertMsg = "- Please choose a relation\n" + alertMsg;
		$("select#relation").focus();
	}
	
	if($("input#giftideaname").val() == "") {
		alertMsg = "- Please enter name for Gift List\n" + alertMsg;
		$("input#giftideaname").focus().css("border-color", "#f00");
	}

	if($("div.widget.new input#password2").val() == "") {
		alertMsg = "- Please confirm password\n" + alertMsg;
		$("input#password2").focus().css("border-color", "#f00");
	}

	if($("div.widget.new input#password").val() == "") {
		alertMsg = "- Please enter a password\n" + alertMsg;
		$("input#password").focus().css("border-color", "#f00");
	}
	
	// Checking if the posswords match each other, but only if the user has entered something in both fields
	if($("div.widget.new input#password").val() != "" && $("div.widget.new input#password2").val() != "" && $("input#password").val() != $("input#password2").val()) {
		alertMsg = "- Passwords don't match\n" + alertMsg;
		$("input#password").focus().css("border-color", "#f00");
		$("input#password2").focus().css("border-color", "#f00");
	}

	// First check if the user has entered an email address, if it is check if it's valid
	if($("input#user_name").val() == "") {
		alertMsg = "- Please enter an Email\n" + alertMsg;
		$("input#user_name").focus().css("border-color", "#f00");
	} else if($("input#user_name").val()) {
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test($("input#user_name").val())) {
			alertMsg = "- Please enter valid Email\n" + alertMsg;
			$("input#user_name").focus().css("border-color", "#f00");
		}
	}

	if($("input#last_name").val() == "") {
		alertMsg = "- Please enter your Last Name\n" + alertMsg;
		$("input#last_name").focus().css("border-color", "#f00");
	}

	if($("input#first_name").val() == "") {
		alertMsg = "- Please enter your First Name\n" + alertMsg;
		$("input#first_name").focus().css("border-color", "#f00");
	}

	return alertMsg;
}
function validateForm2(){
	alertMsg2="";
	if($("input#user_name").val() == "") {
		alertMsg2 = "- Please enter an Email\n" + alertMsg2;
		$("input#user_name").focus().css("border-color", "#f00");
	} else if($("input#user_name").val()) {
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test($("input#user_name").val())) {
			alertMsg2 = "- Please enter valid Email\n" + alertMsg2;
			$("input#user_name").focus().css("border-color", "#f00");
		}
	}
	
	if($("input#last_name2").val() == "") {
		alertMsg2 = "- Please enter your Last Name\n" + alertMsg2;
		$("input#last_name2").focus().css("border-color", "#f00");
	}

	if($("input#first_name2").val() == "") {
		alertMsg2 = "- Please enter your First Name\n" + alertMsg2;
		$("input#first_name2").focus().css("border-color", "#f00");
	}
	
	if($("div.widget input#password2").val() == "") {
		alertMsg2 = "- Please confirm password\n" + alertMsg2;
		$("input#password2").focus().css("border-color", "#f00");
	}

	if($("div.widget input#password").val() == "") {
		alertMsg2 = "- Please enter a password\n" + alertMsg2;
		$("input#password").focus().css("border-color", "#f00");
	}
	
	// Checking if the posswords match each other, but only if the user has entered something in both fields
	if($("div.widget input#password").val() != "" && $("div.widget input#password2").val() != "" && $("input#password").val() != $("input#password2").val()) {
		alertMsg2 = "- Passwords don't match\n" + alertMsg2;
		$("input#password").focus().css("border-color", "#f00");
		$("input#password2").focus().css("border-color", "#f00");
	}
	
	return alertMsg2;
}
function registerIfUsernameAvailable() {
	var data = {user_name : $("input#user_name").val()};

	$.post(webroot + "/widget/widgets/checkUsernameAvailable/", data, function(data, textStatus) {
		// If the user name is available, register the user
		// The reason I'm splitting the return value is becuase CakePHP outputs junk after the value when in debug-mode
		if(data.split("<")[0] == 1) {
			var data = {
						user_name : $("input#user_name").val(),
						password : $("input#password").val(),
						first_name : $("input#first_name").val(),
						last_name : $("input#last_name").val(),
						giftideaname : $("input#giftideaname").val(),
						relation : $("select#relation").val()
					};

			updateWidget("register", data);
			var curO = {};
			curO.pageName = "My Holiday Shopper: User Widget";
			curO.events = "event3";
			trackCall(curO);
		} else {
			alert("Your email address is already registered")
			$("input#user_name").focus().css("border-color", "#f00");
		}
	});
}

// Updates the state of the widget with an ajax-call
function updateWidget(controllerAction, data) {
	// Injecting the right widget into the HTML
	$("#userwidget").load(webroot + "/widget/widgets/" + controllerAction, data, initWidgetInteraction);
	
	// This is for the cancel buttons so that they know what to go back to.
	lastAction = currentAction;
	currentAction = controllerAction;
}

function showPrintBubble(iconClicked) {
	var name = getSelectedName();

	if(name == "My List")
		$("a.print_selected_lists").text("Print " + name);
	else
		$("a.print_selected_lists").text("Print " + name + "'s list");

	var offset = $(iconClicked).offset();
	var offsetJustifier = ($(window).width() - 1250) / 2;

	$("#print_bubble").css("left", offset.left - offsetJustifier - 785);
	$("#print_bubble").css("top", offset.top - 280);
	$("#print_bubble").show();
	$(document).click(hidePrintBubble);
}

function getSelectedName() {
	var name = $("div.widget_item.selected").text();
	name = name.replace("'s Wish List", "");
	name = name.replace(" ( Edit )", "");
	return name;
}

function hidePrintBubble() {
	$("#print_bubble").hide();
	$(document).unbind("click", hidePrintBubble);
}

function showRadioBubble(iconClicked) {
	$("#radio_bubble").show();

	var offset = $(iconClicked).parent().offset();

	var offsetJustifier = ($(window).width() - 1250) / 2;

	$("#radio_bubble").css("left", offset.left - 657 - offsetJustifier);
	$("#radio_bubble").css("top", offset.top - 260);

	$(document).click(hideRadioBubble);

	$("a.list_complete").click(function(e){
		// Remove this click event when done
		$(this).unbind("click");

		// Pick up the id from the id of the row (item_XX)
		var list_id = $(iconClicked).parent().attr("id").split("_")[1];
		
		// Update status using ajax and widget-plugin
		$.post(webroot + "/widget/widgets/listDone/" + list_id);

		// Check the radiobutton
		checkRadio(iconClicked);
		
		// Hide the bubble
		hideRadioBubble();
		return false;
	});
}

function hideRadioBubble() {
	$("#radio_bubble").hide();
	$(document).unbind("click", hideRadioBubble);
	$("a.list_complete").unbind("click");
}


function showAddRecipientBox() {
	var offset = $("div.widget").offset();
	var offsetJustifier = ($(window).width() - 1250) / 2;

	$("#add_recipient").css("left", offset.left - 670 - offsetJustifier);
	$("#add_recipient").css("top", offset.top - 100);
	$("#add_recipient").show();
}

function hideAddRecipientBox() {
	$("#add_recipient").hide();
}

function checkRadio(radioClicked) {
	$(radioClicked).children().each(function(){
		var src = $(this).attr("src");
		src = src.split(".png");
		src = src[0] + "_selected.png";
		$(this).attr("src", src);

		// Replace the containing link with the image to remove "link behavior"
		$(this).parent("a").replaceWith($(this));
	});
}
function showNextProductCol() {
	if(selectedProductCol < $(".product_col").length - 1) {
		selectedProductCol += 1;
		updateProductCols();
	}
}

function showPrevProductCol() {
	if(selectedProductCol > 0) {
		selectedProductCol -= 1;
		updateProductCols();
	}
}

function prevRecipentGroup() {
	if(selectedReceiverGroup > 0) {
		selectedReceiverGroup -= 1;
		updateReceivers();
	}
}

function nextRecipentGroup() {
	if(selectedReceiverGroup < $("div.widget_item_group").length - 1) {
		selectedReceiverGroup += 1;
		updateReceivers();
	}	
}

function updateProductCols() {
	// Set the "previous" button to the right state
	if(selectedProductCol == 0)
		deactivateImageButton("a.prev_btn2 img");
	else
		activateImageButton("a.prev_btn2 img");

	// Set the "previous" button to the right state
	if(selectedProductCol == $(".product_col").length - 1)
		deactivateImageButton("a.next_btn2 img");
	else
		activateImageButton("a.next_btn2 img");

	newColX = selectedProductCol * -162;
	var offset = $("div.widget_clipper").offset();
	$("div.widget_clipper").animate({marginLeft : newColX + "px"}, 1500, null, updateProductColsCallback);
}

function updateReceivers() {
	// Set the "previous" button to the right state
	if(selectedReceiverGroup == 0)
		deactivateImageButton("a.prev_btn img");
	else
		activateImageButton("a.prev_btn img");

	// Set the "previous" button to the right state
	if(selectedReceiverGroup == $("div.widget_item_group").length - 1)
		deactivateImageButton("a.next_btn img");
	else
		activateImageButton("a.next_btn img");

	$("div.widget_item_group").hide().eq(selectedReceiverGroup).show();
	$("div.prev_next span").text((selectedReceiverGroup + 1) + " / " + $("div.widget_item_group").length);
}

function updateProductColsCallback() {
	$("div.prev_next2 span").text((selectedProductCol + 1) + " / " + $(".product_col").length);
}

function deactivateImageButton(img) {
	var oldSrc = $(img).attr("src");
	if(oldSrc && oldSrc.indexOf("_unactive.png") == -1) {
		var srcArr = oldSrc.split(".png");
		var newSrc = srcArr[0] + "_unactive.png";
		$(img).attr("src", newSrc);
	}
}

function activateImageButton(img) {
	var oldSrc = $(img).attr("src");
	if(oldSrc && oldSrc.indexOf("_unactive.png") > -1) {
		var srcArr = oldSrc.split("_unactive.png");
		var newSrc = srcArr[0] + ".png";
		$(img).attr("src", newSrc);		
	}
}

function selectReceiver(receiverClicked) {
	// Loading the entries for the selected list
	var list_id = $(receiverClicked).parent().attr("id").split("_")[1];
	$("div.widget_clipper").load(webroot + "/widget/widgets/entries/" + list_id, null, function(){
		tb_init('a.thickbox');

		selectedProductCol = 0;

		updateProductCols();

		// Set the width of the div containg the products based on the number of products.
		$("div.widget_clipper").css("width", $(".product_col").length * 162 + "px");

		//initWidgetInteraction();
	});
	

	// Removing the "( Edit Link )" from ALL items
	$("div.widget_item").removeClass("selected").children("span").each(function(){
		var oldHtml = $(this).html();
		if(oldHtml.indexOf(' ( <a ') > -1)
			$(this).html(oldHtml.split(' ( <a href="')[0]);
		else if(oldHtml.indexOf(' ( <A ') > -1)
			$(this).html(oldHtml.split(' ( <A href="')[0]);
	});

	// Inserting the "( Edit Link )" in the clicked item
	$(receiverClicked).append(" ( <a href=\"#\">Edit</a> )").children("a").click(function(){
			window.location = webroot + "users/index/" + $(this).parent().parent("div.widget_item").attr("id").split("_")[1];
		}).parent().parent("div.widget_item").addClass("selected");
	
	var name = getSelectedName();

	if(name == "My List")
		$("div.whos_list").text(name);
	else
		$("div.whos_list").text(name + "'s List");
}