/*Version Date: 2010-06-22*/
var animationSpeed = 400;
$(document).ready(function() {
    //Auto-grow textareas
    $("#tableMessage").keyup( function() {
        resizeTextarea(this);
    });

    $("#tableMessage").click( function() {
        resizeTextarea(this);
    });

    $("#notes").keyup( function() {
        resizeTextarea(this);
    });

    $("#tableMessage").click();

    //Close containers
    $("#closeNotes").click(function() {
        $("#NotesContainer").slideUp(animationSpeed);
        $("#notes").val("");
    });

    $("#closeLinks").click(function() {
        $("#LinkContainer").slideUp(animationSpeed);
        $("#urlLink").val("");
    });

    $("#closeLocation").click(function() {
        $("#LocationContainer").slideUp(animationSpeed);
        $("#place").val("");
        $("#location").val("");
    });

    $("#closeVideo").click(function() {
        $("#VideoContainer").slideUp(animationSpeed);
        $("#VideoLink").val("");
    });

    $("#closeDate").click(function() {
        $("#DateContainer").slideUp(animationSpeed);
    });

    $("#closePrice").click(function() {
        $("#PriceContainer").slideUp(animationSpeed);
    });

    $("#closeFile").click(function() {
        $("#FileContainer").slideUp(animationSpeed);
    });

    //Toggle containers
    $("a#AddLink").click(function() {
        $("#closeLinks").show();
        $("#LinkContainer").slideToggle(animationSpeed);
        return false;
    });

    $("a#AddVideo").click(function() {
        $("#closeVideo").show();
        $("#VideoContainer").slideToggle(animationSpeed);
        return false;
    });

    $("a#AddDate").click(function() {
        $("#closeDate").show();
        if (($("#DateContainer").is(":visible")) && ($("#DateContainer #endDateContainer").is(":visible"))) {
            $("#endDateButton").click();
        }
        $("#DateContainer").slideToggle(animationSpeed);
        return false;
    });

    $("a#AddNotes").click(function() {
        $("#closeNotes").show();
        $("#NotesContainer").slideToggle(animationSpeed);
        return false;
    });

    $("a#AddLocation").click(function() {
        $("#closeLocation").show();
        $("#LocationContainer").slideToggle(animationSpeed, function() {
            if ($(this).is(":hidden")) {
                $("#LocationContainer #LocationPlacesContainer").slideUp(function() {
                    $(this).find("select").val("");
                });
            }
        });
        return false;
    });

    $("#AddFiles").click(function() {
        $("#closeFile").show();
        $("#FileContainer").slideToggle(animationSpeed);
        return false;
    });

    $("#AddPriceOptions").click(function() {
        $("#closePrice").show();
        if (!$("#PriceContainer").is(":visible")) {
            if ($.trim($("#productOptionsTable").html()) == "") {
                $("#addProductOption").click();
            }
        }
        $("#PriceContainer").slideToggle(animationSpeed);
        return false;
    });

    $("#LocationContainer #locationPlacesButton").click(function() {
        var $LocationPlacesContainer = $("#LocationContainer #LocationPlacesContainer");
        $LocationPlacesContainer.slideToggle(animationSpeed, function() {
            if ($LocationPlacesContainer.is(":hidden")) {
                $LocationPlacesContainer.find("select").val("");
            }
        });
        return false;
    });

    //Close fields when user backspaces all content
    $("#table_title").keypress(function (e) {
        if ($("#ExtendedFields").is(":hidden")) {
            $("#ExtendedFields").slideDown(animationSpeed);
        }
        if (e.which == 8) {
            if ($(this).val().length == 1) {
                $("#ExtendedFields").slideUp(animationSpeed);
            }
        }
    });

    $("#DateContainer #endDateButton").click(function() {
        var $endDateContainer = $("#DateContainer #endDateContainer");
        $("#DateContainer div:first span").remove();
        if ($endDateContainer.is(":hidden")) {
            $("#DateContainer #display_time").parent().append("<span>End date:</span>");
            $("#DateContainer #display_time span").hide().slideDown();
        }
        $endDateContainer.slideToggle(animationSpeed);
        return false;
    });
});

function twitterDetailsCheck() {
	//the user has checked the Share on Twitter box
	if( window.document.getElementById("share_on_twitter").checked == true ) {
		//check if the user has already saved their twitter details in the dbase
		$.ajax({
			type: "GET",
			url: "/assets/pagelet/checkTwitterDetailsPresent.cfm",
			cache: false,
			success: function(result){
				result = $.trim(result);
				//if the details are already present...
				if (result == "true") {
					//do nothing...yet
					//maybe check is user is real here
				}
				//but if we don't already have both the username and password of the user's twitter account
				else {
					//show the facebox with the form to get and store the user's twitter details
					jQuery.facebox( function() {
						jQuery.get("/assets/pagelet/getUsersTwitterDetails.cfm", function(data) {
							jQuery.facebox(data);
							$("#signin_username").focus();
						});
					});
				}
			}
		});
	}
}

function addImageCaption(imageID) {
	removeCaptionBox();

	var thisCaptionLink = $("#addImageCaption-" + imageID);

	var thisCaptionLinkOffset = thisCaptionLink.offset();
	var thisCaptionBoxTop = thisCaptionLinkOffset.top;
	var thisCaptionBoxLeft = thisCaptionLinkOffset.left + 100;
	var thisCaptionBoxContent;

	$("body").append("<div id='imageCaptionBox'></div>");
	$.get("/assets/pagelet/addImageCaption.cfm", {'imageID': imageID, 'action': 'get'}, function(data) {
		thisCaptionBoxContent = data;
		thisCaptionBoxContent = $.trim(thisCaptionBoxContent);

		$("#imageCaptionBox")
			.css({'top': thisCaptionBoxTop + 'px', 'left': thisCaptionBoxLeft + 'px'})
			.html(data)
			.fadeIn(animationSpeed, function() {
				$("#imageCaptionBox #addImageCaption textarea").focus();
				$("#addImageCaption").submit(function() {
					newCaption = $("#imageCaptionBox textarea").val();
					$.ajax({
						type: "GET",
						url: "/assets/pagelet/addImageCaption.cfm",
						data: "action=set&imageID=" + imageID + "&newCaption=" + newCaption,
						complete: function(XMLHttpRequest, textStatus) {
							data = $.trim(XMLHttpRequest.responseText);
							if (data == "true") {
								//if the caption was saved successfully
								$("#addImageCaption-" + imageID).text("[edit caption]");
								$("#uploadImageRow #imageThumbnail-" + imageID)
									.attr("alt", newCaption)
									.attr("title", newCaption);
								alert("The caption has been successfully saved.\nYou can see it by placing your mouse over the image.");
								removeCaptionBox();
							}
							else {
								//if the pagelet couldn't save the caption
								alert("Sorry, but we couldn't save the caption at this time.\nPlease refresh the page and try again.");
							}
						}
					});
				});
			});
	});
}

function removeCaptionBox() {
	$("#imageCaptionBox").fadeOut(animationSpeed, function() {
		$(this).remove();
	});
}

///

$(document).ready(function() {
    $("#signInFacebox").click(function() {
        jQuery.facebox(function() {
            $.get("/assets/pagelet/signin_ajax.cfm",function(data) {
                jQuery.facebox(data);
                $("#signin_user_name").focus();
            });
        });
    });

    $("#share_on_twitter").change(function() {
        twitterDetailsCheck();
    });

    $("#join_user_name").keyup(function() {
        $.ajax({
            url:"/assets/pagelet/checkUsername.cfm",
            data:"user_name="+$("#join_user_name").val(),
            success:function(response)  {
                response=$.trim(response);
                if(response==0) {
                    $(".screenNameError").remove();
                }
                else {
                    $(".screenNameError").remove();
                    $("#join_user_name").after("<label class='error screenNameError'>Username is unavailable</label>");
                }
            }
        });
    });

    $("#join_email").keyup(function() {
        $.ajax({
            url:"/assets/pagelet/checkEmail.cfm",
            data:"email="+$("#join_email").val(),
            success:function(response)  {
                response=$.trim(response);
                if(response==0) {
                    $(".emailError").remove();
                }
                else {
                    $(".emailError").remove();
                    $("#join_email").after("<label class='error emailError'>Email is unavailable</label>");
                }
            }
        });
    });

    $("#table_title").blur(function(event) {
        $("[for='table_title']").hide();
    });

    if ($("#uploadFile").length > 0) {
        new AjaxUpload("#uploadFile", {
            action: "/assets/pagelet/uploadFile.cfm",
            name: "content_image",
            data: {
                "tempKey": $("#temp_key").val(),
                "action": "upload"
            },
            autoSubmit: true,
            responseType: "text/html",
            onSubmit: function(file, extension) {
                if (!(extension&&/^(pdf)$/.test(extension))) {
                    $("#FileContainer span").html("Sorry, but you can only upload PDF files.");
                    return false;
                }
                $("#FileContainer .loading").show();
            },
            onComplete: function(file, response) {
                $("#FileContainer .loading").hide();
                response = $.trim(response);
                var responseArray = response.split(" | ");
                if (responseArray[0] == "true") {
                    $("#file_link").val(responseArray[2]);
                    $("#FileContainer span").html("Your file was uploaded! You can upload another file, but it will replace the one that you just uploaded.");
                    $("#FileContainer #fileArea").remove();
                    $("#FileContainer span").after("<div id='fileArea' style=\"background:url('/assets/images/pdf_icon.gif') no-repeat scroll left center transparent; margin-top:5px; font-size:0.9em; padding-left:20px;\"><a target='_blank' href='" + responseArray[1] + "'>" + responseArray[2] + "</a> <a href='#' id='removeFile'>[remove]</a><br>(click to open in a new tab/window)</div>");
                    $("#uploadFile").html("<strong>+</strong> CLICK HERE TO UPLOAD A NEW FILE");
                }
                else {
                    $("#FileContainer span").html(response);
                }
            }
        });
    }

    $("#removeFile").live("click", function() {
        $.ajax({
            url: "/assets/pagelet/uploadFile.cfm",
            data: {"temp_key":$("#temp_key").val(), "file":$("#fileArea a").html(), "action":"delete"},
            success: function(data) {
                data = $.trim(data);
                if (data == "true") {
                    $("#file_link").val("");
                    $("#FileContainer span").html("File deleted");
                    $("#FileContainer #fileArea").slideUp(animationSpeed, function() {
                        $(this).remove();
                    });
                }
                else {
                    $("#FileContainer span").html(data);
                }
            }
        });
        return false;
    });
});

function removeJoinOptions() {
    $("#ExtendedFields fieldset").slideUp(300,function() {
        $("#ExtendedFields fieldset").remove();
    });
}