﻿// EONICWEB LTD 2011
// WILL HANCOCK & PERRY HARLOCK

jQuery.fx.off = false,

$(document).ready(function () {

    tooltipTrigger();
    loginListener();
    initialiseEventCarousal();
    // Cat menu stuff 
    if ($("#categoryMenu").exists()) {
        listenerForCatMenu();
    }
    // Ajax in Calendar 
    if ($(".ajaxCalendar").exists()) {
        ajaxCalendar($(".ajaxCalendar"));
    }
    // Bookings Lists
    if ($(".bookingsList").exists()) {
        contactVolunteers();
    }

    if ($("form#EditPage").exists()) {
        // microsite tick listner
        $("input[id^='cMicrosite_']").click(function () {      
            if ($(this).attr('checked')) {
                $("#cXcludeFromSiteNav_1").attr('checked', 'checked');
            }
        });
    }
});


function tooltipTrigger() {
    //Slide Up
    $('.tooltipTrigger').hover(function () {
        $(".cover", this).stop().animate({ top: '0' }, { queue: false, duration: 200 });
    }, function () {
        $(".cover", this).stop().animate({ top: '80px' }, { queue: false, duration: 200 });
    });
}

function initialiseEventCarousal() {
    if ($("#eventCarousel").exists()) {
        /* CAROUSEL */
        //$(".tooltipTrigger").tooltip({ effect: 'slide' });
        /* Innit carousel buttons */

        /* if too few items sto scroll, turn off auto scroll and nav buttons */
        currentItemCount = $("#carousel-items").children(".carousel-item").length;
        if (currentItemCount <= displayShows) {
            iHaveTooFew = true;
            $(".prev").hide();
            $(".next").hide();
            autoValue = 0;
            speedValue = 0;
            goItems = [".next"]; /* breaks the carousel click when too few items */
        }

        /* TURN OFF ANYWAY AS NOT NEEDED */
        $(".prev").hide();
        $(".next").hide();

        $(function () {
            $("#carousel-menu").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev",
                visible: displayShows,
                auto: autoValue,
                speed: speedValue,
                easing: "easeout",
                beforeStart: function () {
                    beforeCallBack();
                },
                afterEnd: function () {
                    afterCallBack();
                    //Slide Up
                    $('.tooltipTrigger').hover(function () {
                        $(".cover", this).stop().animate({ top: '0' }, { queue: false, duration: 200 });
                    }, function () {
                        $(".cover", this).stop().animate({ top: '80px' }, { queue: false, duration: 200 });
                    });

                    //$(".tooltipTrigger").tooltip({ effect: 'slide' });
                },
                btnGo: goItems /* GENERATED AUTOMATICALLY IN HTML SOURCE */
            });
        });

        /* Innit Carousel first item */
        $(".carousel-item").hide();
        $(".carousel-item:first").show().addClass("showing");
        $("#carousel-menu img.1").addClass("selected");

        /* Handle Carousel Clicks */
        $("#carousel-menu .cover").click(function () {
            iWasClicked = true;

            $(".carousel-item").removeClass("showing");
            var wholeClass = $(this).attr("class");
            var clickedItem = wholeClass.substring(6);

            $(".carousel-item[class*='" + clickedItem + "']").addClass("showing");
            itemClicked = clickedItem;

            if (iHaveTooFew) {
                updateItemIndex();
                updateItemInView();
                updateSelectedInMenu();
            }
        });

    }
}

function loginListener() {
    if ($(".loginButton").exists()) {
        $(".loginButton").click(function (clicky) {
            clicky.preventDefault();
            $(this).slideUp();
            $("#loginBox").slideDown();
        });

        // login submit
        $("#loginBox input[type='submit']").click(function () {
            $("#loginBox").slideUp();
            $(".loginButton").html('Logging in...');
            $(".loginButton").slideDown();
        });
    }
}

function listenerForCatMenu() {
    var currentShownEvents = '';
    $("#categoryMenu a").click(function (brap) {
        brap.preventDefault();

        $("#categoryMenu a.active").removeClass('active');
        $(this).addClass('active');

        var eventList = $(this).find(".eventList").attr('title');
        if (eventList == currentShownEvents) {
            $("#" + eventList).slideUp('fast', function () {
                $("#categoryMenu a.active").removeClass('active');
                currentShownEvents = '';
            });
        } else {
            $(".categoryWrapper:visible").slideUp('slow');
            $("#" + eventList).slideDown('slow', function () {
                currentShownEvents = eventList;
            });
        }
    });
}


function ajaxCalendar(loadArea) {
    var today = new Date();
    var dateCode = today.getFullYear() + '-' + today.getMonth() + '-' + today.getDate() + '-' + today.getHours();
    var href = loadArea.attr('title') + '?ajaxCalendar=' + dateCode;
    loadArea.load(href, function () {
        loadArea.find('table').fadeIn(500);
        loadArea.removeClass('loading');
    });
}

/* CAROUSEL CALL BACK FUNCTIONS */
function beforeCallBack() {

}

function afterCallBack() {
    updateItemIndex(); /* manage the counter */
    updateItemInView(); /* manage the current viewed item */
    updateSelectedInMenu(); /* sets the currently selected carousel item t be highlighted in the menu */
    iWasClicked = false; /* aleways remember to reset this to false when done handling the call back*/
}

/* CAROUSEL UTILIS FUNCTIONS */
function updateItemIndex() {


    /* Did the user click? */
    if (iWasClicked) {
        /* the user user clicked an item directly - update index */
        if (iHaveTooFew) {
            currentItemIndex = itemClicked;
        }
        else {
            currentItemIndex = itemClicked;
        }

    }
    else {
        /* the user let it scroll automatically - update index */

        /* check if current item is the last*/
        if (currentItemIndex == currentItemCount) {
            /* it is the last item, cycle */
            currentItemIndex = 1;

        }
        else {
            /* not last item, increment */
            currentItemIndex++;
        }

    }
}

function updateItemInView() {
    /* hide all big items */
    $(".carousel-item").removeClass("showing");
    $(".carousel-item").fadeOut(500);

    /* grabs large item that has class matching currentItemIndex and show it */
    $(".carousel-item").each(function () {
        if ($(this).hasClass(currentItemIndex)) {
            $(this).addClass("showing");
            $(this).fadeIn(500);
        }
    });

}

function updateSelectedInMenu() {
    var itemCount = $("#carousel-items").children(".carousel-item").length;
    $("#carousel-menu img").removeClass("selected");
    $("#carousel-menu img[class*='" + currentItemIndex + "']").addClass("selected");

}


/*  ==============================================================================================  */
/*  ==  Handle user editable content via Ajax  ===================================================  */
/*  ==============================================================================================  */
function getContentForm(args) {

    var submitUrl = "/ewcommon/tools/ajaxContentForm.ashx?ajaxCmd=Edit"

    //alert(submitUrl);
    if (typeof args.targetId != 'undefined') {

        submitUrl += "&type=" + Url.encode(typeof args.type != 'undefined' ? args.type : "")
        submitUrl += "&pgid=" + Url.encode(typeof args.pgid != 'undefined' ? args.pgid : "")
        submitUrl += "&name=" + Url.encode(typeof args.name != 'undefined' ? args.name : "")
        submitUrl += "&id=" + Url.encode(typeof args.id != 'undefined' ? args.id : "")
        submitUrl += "&formName=" + Url.encode(typeof args.formName != 'undefined' ? args.formName : "")
        submitUrl += "&targetId=" + Url.encode(args.targetId)
        submitUrl += "&contentParId=" + Url.encode(typeof args.contentParId != 'undefined' ? args.contentParId : "")
        submitUrl += "&verId=" + Url.encode(typeof args.verId != 'undefined' ? args.verId : "")


        $('#' + args.targetId).html('<div class="loadingLine" style="display:none;">Please wait...</div>');
        $('#' + args.targetId + " .loadingLine").slideDown('fast');


        $('#' + args.targetId).load(submitUrl, function () {
            $('#' + args.targetId).ajaxStop(function () {
                prepareAjaxForm(args.targetId, submitUrl);
            });
        });

    }
    return false;

}
function getUserContentForm(formTargetId, contentType, contentName, pageId, contentId, formName, contentParId) {

    return getContentForm({ targetId: formTargetId, type: contentType, pgid: pageId, name: contentName, id: contentId, formName: formName, contentParId: contentParId });

}
function prepareAjaxForm(formTargetId, submitUrl) {

    // Unbind any previous submit events
    $('#' + formTargetId + ' form').unbind("submit");

    // Bind a new submit event
    $('#' + formTargetId + ' form').bind("submit", function () {
        $(this).ajaxSubmit(
            {

                target: '#' + formTargetId,
                url: submitUrl
            }
        );
        //$('#' + formTargetId).ajaxStop();
        // always return false to prevent standard browser submit and page navigation 
        return false;
    });
}
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
/*  ==  END  handle user editable content via Ajax  =============================================  */

/* When booked, populates the confirmation mailform with the values and submits. */
function confirmBookingEmail(eVRequirementName, eVRequirementDate, eVRequirementStart, eVRequirementEnd) {

    if ($("#bookingConfirmationForm").exists()) {

        var bookingForm = $("#bookingConfirmationForm");

        bookingForm.find("#eVRequirementName").val(eVRequirementName);
        bookingForm.find("#eVRequirementDate").val(eVRequirementDate);
        bookingForm.find("#eVRequirementStart").val(eVRequirementStart);
        bookingForm.find("#eVRequirementEnd").val(eVRequirementEnd);

        bookingForm.find("input[type='submit']").click();

    }

}


/* Contact volunteers */
function contactVolunteers() {

    /* Select all listener */
    $(".bookingsList .selectAll").click(function () {
        var checked = false;
        if ($(this).attr('checked')) {
            checked = true;
        }
        $(this).parents("form").find(".selectUser input[type='checkbox']").each(function () {
            if (checked) {
                $(this).attr('checked', 'checked');
            } else {
                $(this).removeAttr('checked');
            }
        });
    });

    /* Listener for compose buttons */
    $(".bookingsList .doButtons .button").click(function () {
        var userIds = new Array;
        var act = getActFromName(this);
        $(this).parents("form").find("td.selectUser input:checked").each(function () {
            // push selected user id's to array
            userIds.push($(this).val());
        });

        // if users selected
        if (userIds.length > 0) {

            goGetFormAndDisplay(act, userIds);
        } else {
            alert('Please select who you would like to ' + act);
        }
    });
}

function getActFromName(oInput) {
    var string = oInput.name;
    i = string.lastIndexOf('-');
    var act = string.substr(i + 1);
    return act;
}

function goGetFormAndDisplay(act, userIds) {

    // add div to page or not.
    if ($("#vMessagingForm").exists()) {
        $("#vMessagingForm").html('<center><span class="loading-modal">Please wait...</span><center>');
    } else {
        $("body").append('<div id="vMessagingForm" class="dialogPopup"><center><span class="loading-modal">Please wait...</span><center></div>');
    }
    // post load function
    $("#vMessagingForm").dialog({
        width: 600,
        minHeight: 400,
        position: ['center', 'center'],
        modal:true
    });

    /* build up url to ajax */
    var formHTML;
    var formURL = window.location.toString();

    // decide how querystring starts
    if (formURL.indexOf('?') < 0) { formURL = formURL + '?' }
    else { formURL = formURL + '&' };
    // build rest of url
    var random = '&random=' + Math.floor(Math.random() * 10000)
    formURL = formURL + 'getContactForm=' + act + '&userIds=' + userIds.join('-') + random;
   
    $("#vMessagingForm").load(formURL, function () {
        // close listener
        $("#vMessagingForm .modalClose").click(function (clicky) {
            clicky.preventDefault();
            $("#vMessagingForm").dialog('close');
        });
    });

}


function sessionListener() {
    // set interval to check session
    checkSession = setInterval('getSessionCheck()', 12000);
}
function getSessionCheck() {
    var randomVar = Math.floor(Math.random() * 100000);
    var queryString = queryStringBegin();

    // Load in html to trigger session timeout
    var href = window.location + queryString + 'checkSession=' + randomVar
    $("#sessionListener").load(href, function () {
        var sessionStatus = $("#sessionStatus").attr('class');

        //If timed out - Close down this mother!
        if (sessionStatus == 'sessionclosed') {
            // stop interval
            clearInterval(checkSession);

            // model loged off box
            $("#vMessagingForm").dialog('close');
            $('#sessionStatus .dialogPopup').dialog({
                width: 600,
                minHeight: 400,
                position: ['center', 'center'],
                modal: true
            });
        }
    });
}

function queryStringBegin() {
    var symbol = '?';
    var currentURL = String(window.location);
    if (currentURL.indexOf('?') > -1){
        symbol = '&';
    }
    return symbol;
} 
