// Cufon Settings
$(function () {
	// Cufon Configuration
	Cufon.set('fontFamily', 'avenir');
	Cufon.replace('h1', { color: 'rgb(0,0,0)' });

	Cufon.replace('.avenir');
	Cufon.replace('.avenir-51', { color: 'rgb(51,51,51)' });

	// Specific Replacements
	Cufon.replace('#language-options a', {
		color: 'rgb(51,51,51)',
		hover: { color: 'rgb(175,175,175)' }
	});

	Cufon.replace('#navigation-main li a', {
		color: 'rgb(255,255,255)',
		textShadow: '1px 2px rgba(0,0,0,.4)'
    });

    Cufon.replace('.tpc-rmshare .tpc-lt-text', {
        color: 'rgb(255,255,255)',
        textShadow: '1px 2px rgba(0,0,0,.4)'
    });

	Cufon.replace('#tri-block-mbmmmw .inner-shell a span', {
		color: 'rgb(255,255,255)',
		textShadow: '1px 2px rgba(0,0,0,.4)'
	});


});

var _MOMSCal = {
	global_evts: null
};

$(document).ready(function () {

    // Drop Down Nav
    if ($('#navigation-main').length > 0) {

        // Only do things if a subnav exists
        $('ul.topnav li').each(function () {
            // Only Do Shiz if a subnav exists
            if ($(this).find('ul.subnav').length > 0) {
                $(this).hover(
					function () { $(this).find("ul.subnav").slideDown(300); },
					function () { $(this).find("ul.subnav").slideUp(150); }
				);
            }
        });
    }

    if ($('#fd-factoidOfDay').length > 0) {
        var str = document.URL;
        var url_check = str.indexOf('/es');

        if (url_check == -1) {
            $('#fd-factoidOfDay').text('factoid of the day');
        }
        else {
            $('#fd-factoidOfDay').text('factoid del dia');
        }
    }

    // Home Page Factoid Day
    if ($('#fd-day').length > 0) {

        var str = document.URL;
        var url_check = str.indexOf('/es');

        if (url_check == -1) {
            today = new Date();
            numDay = today.getDay(); // Returns a number 0-6
            var weekDays = new Array(7);
            weekDays[0] = "Sunday's ";
            weekDays[1] = "Monday's ";
            weekDays[2] = "Tuesday's ";
            weekDays[3] = "Wednesday's ";
            weekDays[4] = "Thursday's ";
            weekDays[5] = "Friday's ";
            weekDays[6] = "Saturday's ";
            $('#fd-day').text(weekDays[numDay]);
            Cufon.replace('#fd-inner', {
                color: 'rgb(255,255,255)',
                textShadow: '1px 2px rgba(0,0,0,.4)'
            });
        }
        else {
            today = new Date();
            numDay = today.getDay(); // Returns a number 0-6
            var weekDays = new Array(7);
            weekDays[0] = "Domingo ";
            weekDays[1] = "Lunes ";
            weekDays[2] = "Martes ";
            weekDays[3] = "Miércoles ";
            weekDays[4] = "Jueves ";
            weekDays[5] = "Viernes ";
            weekDays[6] = "Sábado ";
            $('#fd-day').text(weekDays[numDay]);
            Cufon.replace('#fd-inner', {
                color: 'rgb(255,255,255)',
                textShadow: '1px 2px rgba(0,0,0,.4)'
            });
        }
    }
    
    
    
//    // Home Page Factoid Day
//    if ($('#fd-day').length > 0) {
//        today = new Date();
//        numDay = today.getDay(); // Returns a number 0-6
//        var weekDays = new Array(7);
//        weekDays[0] = "Sunday";
//        weekDays[1] = "Monday";
//        weekDays[2] = "Tuesday";
//        weekDays[3] = "Wednesday";
//        weekDays[4] = "Thursday";
//        weekDays[5] = "Friday";
//        weekDays[6] = "Saturday";
//        $('#fd-day').text(weekDays[numDay]);
//        Cufon.replace('#fd-inner', {
//            color: 'rgb(255,255,255)',
//            textShadow: '1px 2px rgba(0,0,0,.4)'
//        });
//    }

    // Home Page Slideshow
    if ($('#panel-top-slides').length > 0) {
        $("#ptsc-items").tabs("#top-slides > .top-slide", {
            effect: 'fade',
            fadeOutSpeed: 'fast',
            fadeInSpeed: 'slow',
            current: 'active',
            event: 'mouseover',
            tabs: 'li',
            rotate: true
        }).slideshow();
        var ptsapi = $("#ptsc-items").data("tabs");
        $("#ptsc-prev").click(function () { ptsapi.prev(); });
        $("#ptsc-next").click(function () { ptsapi.next(); });

        // Tooltips
        $('.ptsc-item a').tooltip({
            effect: 'slide',
            tipclass: 'ptsc-tip',
            delay: 100,
            predelay: 100
        });
    }

    // Home Page MBMMMW Rollovers



    // Home Page Full Calendar
    if ($('#hec-calendar').length > 0) {
        $('#hec-calendar').each(function () {
            $(this).fullCalendar({
                // Params
                height: 220,
                weekMode: 'fixed',
                header: {
                    left: 'prev',
                    center: 'title',
                    right: 'next'
                },
                buttonText: {
                    prev: '',
                    next: ''
                },
                events: '/Ajax/PMG.GoogleCal.GCalFacade.GetCalendarEventsJson.ashx'
            });
        });
    }

    // Home Page Events List
    if ($('#events-recent').length > 0) {

        $.ajax({
            url: '/Ajax/PMG.GoogleCal.GCalFacade.GetGlobalEventsJson.ashx',
            success: function (data) {
                var json = $.parseJSON(data);
                var evts = $('#events-recent');

                // sort them by ASC
                json.sort(function (a, b) {
                    if (a.start_time > b.start_time) return 1;
                    if (a.start_time < b.start_time) return -1;
                    return 0;
                });

                // add each item to events-recent ul
                // TODO: sort
                $.each(json, function (idx, value) {
                    var start = Date.parse(value.start_time);

                    // added todaysDate to verify against the dates in the db
                    var todaysDate = new Date();
                    todaysDate.setHours(0, 0, 0, 0);
                    // added the compare <= here to hide past events
                    if (todaysDate.valueOf() <= start.valueOf()) {
                        var html = '<li>' +
										 '  <div class="er-date">' +
										 '		<span class="erd-month">' + start.toString('MMM') + '</span>' +
										 '		<span class="erd-day avenir">' + start.toString('dd') + '</span>' +
										 '	</div>' +
										 '	<a class="er-add" href="#" id="' + value.id + '"></a>' +
										 '	<p class="er-title">' + value.title + '</p>' +
										 '</li>';

                        evts.append(html);
                    }
                });

                $('.er-add').click(function (e) {
                    e.preventDefault();
                    window.location = '/calendar?addEvt=' + e.currentTarget.id;
                });
            }
        });

    }

    // Calendar Landing Page Full Calendar
    if ($('#cal-landing').length > 0) {

        // evts are pulled in from the ajax calendar source below
        // TODO: don't refresh events from server on every view change
        $('#cal-landing').each(function () {
            $(this).fullCalendar({
                // Params
                height: 368,
                weekMode: 'fixed',
                header: {
                    left: 'today prev next',
                    center: 'title',
                    right: 'basicDay basicWeek month'
                },
                events: '/Ajax/PMG.GoogleCal.GCalFacade.GetCalendarEventsJson.ashx'
            });
        });

        $('#lcu-refresh').click(function () {
            $('#cal-landing').fullCalendar('refetchEvents');
        });

        $('#lcu-create-btn').fancybox({
            overlayColor: 'rgb(51,51,51)',
            onStart: function (atag) {
                //				var evt_id = atag[0].id;
                //				var this_data;

                //				$.each(_MOMSCal.global_evts, function (idx, evt_data) {
                //					if (evt_data != null && evt_data != undefined && evt_data.id == evt_id) {
                //						this_data = evt_data;
                //						return;
                //					}
                //				});

                //				var start = Date.parse(this_data.start_time);
                //				var end = Date.parse(this_data.end_time);
                //				var when_str = start.toString('dddd, MMMM d yyyy, h:mmtt') + ' - ' + end.toString('dddd, MMMM d yyyy, h:mmtt')

                //				$('#title-content').text(this_data.title);
                //				$('#when-content').text(when_str);
                //				$('#where-content').text(this_data.location);
                //				$('#description-content').text(this_data.description);
                //				$('#link-evt-id').attr('value', evt_id);
            }
        });
    }

    // Calendar Landing Page Pagable Events List
    if ($('#tpt-events').length > 0) {

        $("#tpt-events").scrollable({
            vertical: true,
            mousewheel: true,
            speed: 500
        });

        var elapi = $("#tpt-events").data("scrollable");
        $("#tpt-e-c-prev").click(function () { elapi.prev(); });
        $("#tpt-e-c-next").click(function () { elapi.next(); });

        // NOTE: we assume here that the scrollable control will be initialized
        // faster than we can make a web service call & parse/add results
        $.ajax({
            url: '/Ajax/PMG.GoogleCal.GCalFacade.GetGlobalEventsJson.ashx',
            success: function (data) {
                var json = $.parseJSON(data);
                _MOMSCal.global_evts = json;

                // sort the objects by start_time inc                
                json.sort(function (a, b) {
                    if (a.start_time > b.start_time) return 1;
                    if (a.start_time < b.start_time) return -1;
                    return 0;
                });


                // add each item to scrollable
                // TODO: sort by date
                // TODO: add to proper groups / fix paging (see below call to seekTo)
                $.each(json, function (idx, value) {
                    var start = Date.parse(value.start_time);

                    var todaysDate = new Date();
                    todaysDate.setHours(0, 0, 0, 0);
                    // added the compare <= here to hide past events
                    if (todaysDate.valueOf() <= start.valueOf()) {
                        var html =
                     '<div class="event">' +
					 '  <a class="cal-add" href="#cal-link-form" id="' + value.id + '">' +
                     '    <div class="ev-date">' +
                     '      <div class="evd-month">' + start.toString('MMM') + '</div>' +
                     '      <div class="evd-day avenir">' + start.toString('dd') + '</div>' +
                     '    </div>' +
					 '    <div class="ev-desc">' +
					 '			<div class="evd-title avenir">' + value.title + '</div>' +
					 '			<div class="evd-datetime">' + start.toString('ddd, MMMM dd') + ' at ' + start.toString('HH.mmtt') + '</div>' +
					 '			<div class="evd-location">' + value.location + '</div>' +
					 '		</div>' +
					 '		<div class="ev-plus"></div>' +
					 '	</a>' +
					 '</div>';

                        elapi.addItem(html);
                    }
                });

                // TODO: seek to the beginning of the list
                // elapi.seekTo(json.length - 1);
                elapi.seekTo(0);


                // wire add clicks to show lightbox
                $('.cal-add').fancybox({
                    onStart: function (atag) {
                        var evt_id = atag[0].id;
                        var this_data;

                        $.each(_MOMSCal.global_evts, function (idx, evt_data) {
                            if (evt_data != null && evt_data != undefined && evt_data.id == evt_id) {
                                this_data = evt_data;
                                return;
                            }
                        });

                        var start = Date.parse(this_data.start_time);
                        var end = Date.parse(this_data.end_time);
                        var when_str = start.toString('dddd, MMMM d yyyy, h:mmtt') + ' - ' + end.toString('dddd, MMMM d yyyy, h:mmtt')

                        $('#title-content').text(this_data.title);
                        $('#when-content').text(when_str);
                        $('#where-content').text(this_data.location);
                        $('#description-content').text(this_data.description);
                        $('#link-evt-id').attr('value', evt_id);
                    }
                });

                // wire link modal lightbox btns
                $('#link-cancel-btn').click(function (e) {
                    e.preventDefault();
                    $.fancybox.close();
                });
                $('#link-submit-btn').click(function (e) {
                    e.preventDefault();

                    var event_id = $('#link-evt-id').attr('value');
                    $.ajax({
                        url: '/Ajax/PMG.GoogleCal.GCalFacade.AddCalendarEvent.ashx?evtId=' + event_id,
                        success: function () {
                            $('#cal-landing').fullCalendar('refetchEvents');
                        }
                    });
                    $.fancybox.close();
                });

                // wire create/edit modal lightbox btns
                $('#edit-cancel-btn').click(function (e) {
                    e.preventDefault();
                    $.fancybox.close();
                });
                $('#edit-submit-btn').click(function (e) {
                    e.preventDefault();                    

                    var start = $('#start-date').attr('value') +
						' ' + $('#start-time-h').val() +
						':' + $('#start-time-m').val() +
									$('#start-time-am').val();
                    var end = $('#end-date').attr('value') +
						' ' + $('#end-time-h').val() +
						':' + $('#end-time-m').val() +
									$('#end-time-am').val();

                    //					var event_id = $('#link-evt-id').attr('value');
                    var event_id = '';
                    var post_url = "/Ajax/PMG.GoogleCal.GCalFacade.AddOrEditEvent.ashx?id=" + event_id;
                    post_url += "&title=" + $('#edit-title-content').attr('value');
                    post_url += "&startTime=" + start;
                    post_url += "&endTime=" + end;
                    post_url += "&where=" + $('#edit-where-content').attr('value');
                    post_url += "&description=" + $('#edit-description-content').attr('value');
                    //					post_url = encodeURIComponent(post_url);

                    $.ajax({
                        url: post_url,
                        success: function () {
                            $('#cal-landing').fullCalendar('refetchEvents');
                        }
                    });
                    $.fancybox.close();
                });

                // wire create/edit datepickers
                $(":date").dateinput({ format: 'yyyy-mm-dd' });

                // finally, if we have a request to add a specific event, do that now
                if (window.location.search != "") {
                    var in_eid = window.location.search.substr(8);
                    $('.cal-add').each(function (idx, value) {
                        if (in_eid == value.id) {
                            $(value).click();
                            return;
                        }
                    });
                }
            }

        });

    }

    // Tabbed x3 Page Layout jQ
    if ($('#tx3-c-tabs').length > 0) {
        $(".tx3-tc").tabs("#tx3-c-tabs > .tx3-c-tab", { effect: 'slide' }); // Initiate Tabs 
        var tx3api = $(".tx3-tc").data("tabs"); // API can be accessed now
        $("#tx3-tc-next").click(function () { tx3api.next(); }); // Next Button Functionality 


        //bs added to hide next button on the 3rd tab
        tx3api.onClick(function () {
            //if index is the 3rd tab, then hide the tx3-tc-next button
            //p.show { display: block }
            //p.hide { display: none; }
            var idx = tx3api.getIndex();
            if (idx == 2)// 0 based?
            {
                $("#tx3-tc-next").css('display', 'none');
            }
            else {
                $("#tx3-tc-next").css('display', 'block');
            }
        });

    }

    // Font Size Tool
    var originalFontSize = '1em';
    var smallFontSize = '0.8em';
    var largeFontSize = '1.2em';

    // Only Show HT-TextSize Tool on Generic and Detail Pages
    if ($('#header-tools').length > 0) {
        $('#header-tools').each(function () {
            if ($(this).find('#ht-textsize').length > 0) {
                $(this).find('#ht-textsize').css('display', 'none');
            }
            if ($('body').hasClass('generic') || $('body').hasClass('detail')) {
                $(this).find('#ht-textsize').css('display', 'block');
            }
        });

        // Smaller only on Generic and Detail C-Inner
        $("#textsize-options #option-small").click(function () {
            if ($('body').hasClass('generic') || $('body').hasClass('detail')) {
                $('body .c-inner').css('font-size', smallFontSize);
            }
        });

        // Original only on Generic and Detail C-Inner
        $("#textsize-options #option-reset").click(function () {
            if ($('body').hasClass('generic') || $('body').hasClass('detail')) {
                $('body .c-inner').css('font-size', originalFontSize);
            }
        });

        // Larger only on Generic and Detail C-Inner
        $("#textsize-options #option-large").click(function () {
            if ($('body').hasClass('generic') || $('body').hasClass('detail')) {
                $('body .c-inner').css('font-size', largeFontSize);
            }
        });

    }

    // External Links Fancybox Handler
    // Creating custom :external selector
    $.expr[':'].external = function (obj) {
        return !obj.href.match(/^mailto\:/)
		    && (obj.hostname != location.hostname);
    };

    // Fancybox the External Links
    $('a:external').each(function () {

        $(this).addClass('external');

        var thisExtHref = $(this).attr('href');
        var thisPriMsg;        
        var thisSecMsg;
        
        var str = document.URL;
        var url_check = str.indexOf('/es');

        if (url_check == -1) {
            thisPriMsg = "<h2>Are you sure you want to navigate away from this page?</h2>";
            thisSecMsg = "<h2>Press OK to continue, or close this dialog to stay on the current page.</h2>";
        }
        else {
            thisPriMsg = "<h2>ESP Are you sure you want to navigate away from this page?</h2>";
            thisSecMsg = "<h2>ESP Press OK to continue, or close this dialog to stay on the current page.</h2>";
        }
        
        
        
        
        
        
        $(this).fancybox({
            'hideOnContentClick': true,
            titleShow: false,
            content: '<div class="fb-ext-modal">' + thisPriMsg + thisSecMsg + '<a class="fb-ext-ok" href="' + thisExtHref + '" target="_blank" /></div>'
        });

    });

    // Activate Cufon (Always leave this as Last)
    Cufon.now();

});


