/*
Project:	St Mary's College PPU
Created:	13/06/11
Author:		IPAG (Ireland) Ltd. (KG)
*/

$(document).ready(function() {
    // Member search autocomplete
    $(function() {
        $("#SearchMembersInc_fullName").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "EmployeeList.asmx/FetchEmailList",
                    data: "{ 'mail': '" + request.term + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function(data) { return data; },
                    success: function(data) {
                        response($.map(data.d, function(item) {
                            return {
                                value: item.Email
                            }
                        }))
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 2
        });
    });

    // Fancy text swapper for input boxes
    $.each("input[type=text]", function(index) {
        if (!$(".noreplace").length > 0)
            clearInputDefaults($("input[type=text]").eq(index).attr("id"));
    });
    $.each("input[type=password]", function(index) {
        if (!$(".noreplace").length > 0)
            clearInputDefaults($("input[type=password]").eq(index).attr("id"));
    });

    $("input[type=password]").blur(function() {
        if ($(this).val() != "")
            $(this).css('background-image', 'none');
    });

    // Make the events links block level
    if ($("#boxEvents").length > 0) {
        $("#boxEvents li").each(function(index) {
            if ($(this).attr("rel").length > 0) {
                $(this).bind({
                    click: function() {
                        window.location = "News.aspx?NID=" + $(this).attr("rel");
                    },
                    mouseenter: function() {
                        $(this).addClass("hover");
                    },
                    mouseleave: function() {
                        $(this).removeClass("hover");
                    }
                });
            }
        });
    }
    // Make the Gallery listings links block level
    if ($(".galleryList").length > 0) {
        $(".galleryList").each(function(index) {
            if ($(this).attr("rel").length > 0) {
                $(this).bind({
                    click: function() {
                        window.location = "Gallery.aspx?GID=" + $(this).attr("rel");
                    },
                    mouseenter: function() {
                        $(this).addClass("hover");
                    },
                    mouseleave: function() {
                        $(this).removeClass("hover");
                    }
                });
            }
        });
    }
    if ($("#galleryImage a[rel=gallery]").length > 0) {
        $("a[rel=gallery]").fancybox({
            'titlePosition': 'over',
            'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
            }
        });
    }

    // Mega Menu
    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
        interval: 100, // number = milliseconds for onMouseOver polling interval
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
        timeout: 500, // number = milliseconds delay before onMouseOut
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)
    };

    $("#navTop ul li .sub").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default
    $("#navTop ul li").hoverIntent(config); //Trigger Hover intent with custom configurations

    //    // fancyImage - Homepage
    //    if ($("#rowImage").length > 0) {
    //        i = 0;
    //        imageArrayHome = [
    //			'url(\'images/template/homeImage2.jpg\')',
    //			'url(\'images/template/homeImage3.jpg\')',
    //            'url(\'images/template/homeImage4.jpg\')',
    //        //'url(\'images/template/homeImage5.jpg\')',
    //			'url(\'images/template/homeImage1.jpg\')'
    //		];
    //        window.setInterval(function() {
    //            fancyImage(imageArrayHome[i], "#rowImage");
    //            i++;
    //            if (i == imageArrayHome.length) { i = 0; }
    //        }, 10000);
    //    }
    // Carousel - Sponsors
    if ($("#buttonsSponsors").length > 0) {
        $("#buttonsSponsors").jcarousel({
            auto: 4,
            wrap: 'circular',
            scroll: 6,
            size: 10,
            initCallback: buttonsSponsors
        });
    }
    function buttonsSponsors(carousel) {
        // Disable autoscrolling if the user clicks the prev or next button.
        carousel.buttonNext.bind('click', function() {
            carousel.startAuto(0);
        });

        carousel.buttonPrev.bind('click', function() {
            carousel.startAuto(0);
        });

        // Pause autoscrolling if the user moves with the cursor over the clip.
        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });
    }

    // Homepage login box (membership box)
    $("#membershipLoginButton").click(function(e) {
        e.preventDefault();
        $("#membershipOptions").fadeOut("slow", function() {
            $("#membershipLogin").fadeIn("slow").show();
        });
    });

    $("#membershipLoginSubmit").click(function(e) {
        e.preventDefault();
        userLogin();
    });

    function userLogin() {
        $("#membershipLoginFail").hide();
        $("#membershipLoginLoading").show();
        var postData = {
            username: $("#membershipUsername").val(),
            password: $("#membershipPassword").val()
        }
        $.ajax({
            type: "POST",
            url: "EmployeeList.asmx/login",
            data: postData,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "xml",
            success: homeLoginSuccess,
            error: homeLoginError
        });
    }
    function homeLoginSuccess(data) {
        $("#membershipFullName").text($(data).find("firstName").text() + " " + $(data).find("lastName").text());
        $("#membershipEmail").text($(data).find("email").text());
        $("#membershipExpiry").text("Expiry: " + $(data).find("expiry").text());
        imagePath = "User_Pictures/" + $(data).find("photo").text();
        //console.log("Image Path: " + imagePath);
        var profileImg = new Image();
        //console.log("Image placeholder created");
        profileImg.onload = function() {
            //console.log("Image Exists");
            $("#membershipPhoto").html("<img src='" + imagePath + "' height='105' alt='' />");
        };
        profileImg.onerror = function() {
            //console.log("Image DOES NOT exist");
            $("#membershipPhoto").html("<img src='User_Pictures/noImage.jpg' height='105' alt='' />");
        };
        //console.log("Testing image");
        profileImg.src = imagePath; // fires off loading of image

        $("#membershipLoginLoading").hide();
        $("#membershipLogin").fadeOut("slow", function() {
            $("#membershipLoginSuccess").fadeIn("slow", function() {
                $("#loginout a").fadeOut("slow", function() {
                    $("#loginout").html("<a href='Logout.aspx' class='button logout'>Logout</a><a href='My_Profile.aspx' class='button myProfile-blue'>My Profile</a>").fadeIn("slow");
                });
            });
        });
    }
    function homeLoginError(data) {
        $("#membershipLoginLoading").hide();
        $("#membershipLoginFail").text("Login failed. Please check your credentials and try again.");
        $("#membershipLoginFail").fadeIn("slow");
    }

    $(function() {
        if ($("#userLoggedIn").val() == "true") {
            $("#membershipLoginLoading, #membershipOptions, #membershipLogin").hide();
            $("#membershipFullName").text($("#sessionFirstName").val() + " " + $("#sessionLastName").val())
            $("#membershipEmail").text($("#sessionEmail").val());
            $("#membershipExpiry").text("Expiry: " + $("#sessionExpiry").val());
            $("#membershipPhoto").html("<img src='User_Pictures/" + $("#sessionPhoto").val() + "' width='105' />");

            $("#membershipLoginSuccess").show();
        }
    });

    if ($("#myProfile table").length > 0) {
        $("#myProfile table tr:nth-child(odd)").addClass("alt");
    }
    // Facebook and LinkedIn help
    if ($(".profileHelpLink").length > 0) {
        //profileHelp

        $(".profileHelpLink").bind("click", function(e) {
            //alert("Clicked");
            e.preventDefault();
            $("#profileHelp").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                minHeight: 250,
                width: 400
            });
            //alert("dialog");
        });
    }

    $('textarea').autoResize({
        // On resize:
        onResize: function() {
            $(this).css({ opacity: 0.8 });
        },
        // After resize:
        animateCallback: function() {
            $(this).css({ opacity: 1 });
        },
        // Quite slow animation:
        animateDuration: 300,
        // More extra space:
        extraSpace: 40
    });

    if ($("#CVVinfoRegisterLink").length > 0) {
        $("#CVVinfoRegisterLink").bind("click", function(e) {
            //alert("Clicked");
            e.preventDefault();
            $("#CCVInfoReg").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                minHeight: 250,
                width: 320
            });
            //alert("dialog");
        });
    }
    if ($(".fullMemberHelp, .halfMemberHelp, .notMemberHelp").length > 0) {
        $(".fullMemberHelp, .halfMemberHelp, .notMemberHelp").bind("click", function(e) {
            //alert("Clicked");
            e.preventDefault();
            $("#memberTypeHelp").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                minHeight: 250,
                width: 400
            });
            //alert("dialog");
        });
    }

    /* Shop */
    if ($("#shop").length > 0) {
        $(".shopProduct:odd").addClass("alt");

        if ($("#CVVinfo").length > 0) {
            $("#CVVinfo").bind("click", function(e) {
                //alert("Clicked");
                e.preventDefault();
                $("#CVVinfoDialog").dialog();
                //alert("dialog");
            });
        }

        if ($("#deliveryInfoDialog").length > 0) {
            $("#deliveryInfo").bind("click", function(e) {
                //alert("Clicked");
                e.preventDefault();
                $("#deliveryInfoDialog").dialog();
            });
        }
    }

    if ($("table.generic").length > 0)
        $("table.generic tr:nth-child(even)", this).addClass("alt");

    //$("select").chosen();

    // BookEventTickets - Select the number of tickets you want, update the price and guest numbers
    if ($("#eventTicketPrices").length > 0) {
        /* CCV Info */
        $("#CCVInfoLink").bind("click", function(e) {
            e.preventDefault();
            $("#CCVInfo").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                minHeight: 250,
                width: 320
            });
        });

        var totalGuests = 0;
        var amount, price = 0;
        var cat1Total = 0;
        var cat2Total = 0;
        var cat3Total = 0; // A category for each ticket type
        var totalPrice = 0;

        $("#eventTicketPrices select").change(function() {
            price = $(this).attr("rel"); // Price of the selected ticket
            amount = $("option:selected", this).val(); // Number of tickets selected
            total = amount * price; // Total price of this ticket

            if ($(this).attr("id") == "ddTicketSingle") {
                cat1Total = total;
            } else if ($(this).attr("id") == "ddTicketTable") {
                cat2Total = total; // Eight people are on a single ticket of this type
            }
            else if ($(this).attr("id") == "ddTicketStudent") {
                cat3Total = total;
            }
            else {
                //console.log("Error updating the total number of guests");
            }
            //console.log("Cat1: " + parseInt(cat1Total) + " Cat2: " + parseInt(cat2Total) + " Cat3: " + parseInt(cat3Total));
            totalPrice = parseInt(cat1Total) + parseInt(cat2Total) + parseInt(cat3Total);
            //console.log(totalPrice);
            $("#ticketTotalPrice").html("&euro;" + totalPrice);
            //totalGuests = parseInt(cat1Total) + parseInt(cat2Total) + parseInt(cat3Total);
            //console.log("Total guests: " + totalGuests);
            //console.log("Price: " + price + " Amount: " + amount + " Total:" + total);
            $(this).next("span").html("<strong>Sub Total:&nbsp;</strong>&euro;" + total + "");
        });
    }

    /* Members Search Page */

    if ($("#memberSearchPage").length > 0) {
        clearSpecialInputs("txtFirstName", "Name");
        clearSpecialInputs("txtLastName", "Surname");
        clearSpecialInputs("txtYearLeft", "Year Left");
        // Dialog box
        $(".listView").click(function(e) {
            e.preventDefault();
            // Nasty ...
            var userIDLink = $(this).attr("class");
            var userID = userIDLink.split(" ");
            //alert("User ID: " + userID[2]);
            popup(userID[2]);
        });

        $("#closeButton").click(function() {
            //$('#dialog-overlay, #dialog-box').hide();
            $('#dialog-box').hide();
            return false;
        });

        // if user resize the window, call the same function again
        // to make sure the overlay fills the screen and dialogbox aligned to center
        $(window).resize(function() {
            //only do it if the dialog box is not hidden
            if (!$('#dialog-box').is(':hidden')) popup();
        });

        //Popup dialog
        function popup(userID) {
            $("#dialog-message").hide();
            $("#dialog-error").hide();
            $("#dialog-loading").show();
            // get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            // calculate the values for center alignment
            var dialogTop = (maskHeight / 3) - ($('#dialog-box').height());
            var dialogLeft = (maskWidth / 2) - ($('#dialog-box').width() / 2);

            // assign values to the overlay and dialog box
            //$('#dialog-overlay').css({ height: maskHeight, width: maskWidth }).show();
            $('#dialog-box').css({ top: "284px", left: dialogLeft + 42 }).show();

            // get the user's information
            $.ajax({
                type: "POST",
                url: "EmployeeList.asmx/getUserInfo",
                data: { userID: userID },
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                dataType: "xml",
                success: popuploadSuccess,
                error: popuploadError
            });
        }
        function popuploadSuccess(data) {
            //console.log("Load success");
            $xml = $(data);
            $("#user-name span").text($xml.find("name").text());
            $("#user-companyName span").text($xml.find("companyName").text());
            $("#user-companyCategory span").text($xml.find("companyCategory").text());
            $("#user-companyText span").text($xml.find("companyText").text());
            var img = new Image();
            img.onload = function() {
                //console.log("Image Exists");
                $("#user-picture").html("<img src='User_Pictures/" + $xml.find("photo").text() + "' height='105' alt='" + $xml.find("name").text() + "' />");
            };
            img.onerror = function() {
                //console.log("Image DOES NOT exist");
                $("#user-picture").html("<img src='User_Pictures/noImage.jpg' height='105' alt='" + $xml.find("name").text() + "' />");
            };
            img.src = "User_Pictures/" + $xml.find("photo").text(); ; // fires off loading of image
            $('#moreInfoLink').bind('click', function() {
                window.location = "User_Details.aspx?ID=" + $xml.find("ID").text();
            });
            $("#dialog-loading").fadeOut("fast", function() {
                $("#dialog-message").fadeIn("fast").show();
            });
        }
        function popuploadError(request, status, error) {
            $("#dialog-loading").fadeOut("fast", function() {
                $("#dialog-error").fadeIn("fast").show();
            });
        }
    } // memberSearchPage()
});                 // ready()

/* Fancy Image */
function fancyImage(image, imageID) {
    $(imageID).fadeOut(400, function() {
        $(imageID).css("background-image", image);
        $(imageID).fadeIn(800, function() { });
    });
    return false;
}

/* Fancy text swapper */
function clearInputDefaults(inputID) {
    if ($("#" + inputID).length > 0) {
        var ctrlID = ("#" + inputID);
        var defTxt = $(ctrlID).val();
        $(ctrlID).focus(function() { if ($(this).val() == defTxt) $(this).val(''); });
        $(ctrlID).blur(function() { if ($(this).val() == '') $(this).val(defTxt); });
    }
}
/* Fancy text swapper */
function clearSpecialInputs(inputID, inputDefaultValue) {
    if ($("#" + inputID).length > 0) {
        var ctrlID = ("#" + inputID);
        $(ctrlID).focus(function() { if ($(this).val() == inputDefaultValue) $(this).val(''); });
        $(ctrlID).blur(function() { if ($(this).val() == '') $(this).val(inputDefaultValue); });
    }
}

/* Mega Menu */
function megaHoverOver() {
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    if ($(this).find(".sub").length > 0) {
        $('#overlay').fadeTo('fast', 0.4);
    }

    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery);

    if ($(this).find(".row").length > 0) { //If row exists...
        var biggestRow = 0;

        $(this).find(".row").each(function() {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if (rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({ 'width': biggestRow }); //Set width
        $(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin
    } else { //If row does not exist...
        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({ 'width': rowWidth }); //Set Width
    }
}
function megaHoverOut() {
    $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
        /*
        var o = $(this).find(".sub").offset();
        var p = $("#wrapperContent").offset();
        var pw = document.getElementById("wrapperContent").clientWidth;
        var tw = rowWidth;
        o.left = (o.left - p.left);
        var tml = ((tw + o.left) - pw);
        alert("o=" + o + " p=" + p + "pw= " + pw + "tw= " + tml);
        $(this).find(".sub").css({"width" : rowWidth}).css({"margin-left":"-" + (tml - 49) + "px"});
        */
        $(this).hide();  //after fading, hide it
        $('#overlay').fadeTo('fast', 0, function() { $('#overlay').hide(); });
    });
}

// Server messsaging system
