jQuery(document).ready(function() {

    //http://arshaw.com/fullcalendar/docs/
    jQuery('div#calendar').fullCalendar(getCalOptions());
    //they may call from hidden menu
   
    especialsJquery();    

    //add custom stuff to calendar header
    insertLegendButtonAfterHeaderButton('today');

    jQuery("a[rel='ColorBox']").colorbox({
        transition: "elastic"
    });

    jQuery('#pageCounter').ready(function() {
        //#Container .image-div --> #Container img
        jQuery("#Container .image-div").quickpaginate({
            perpage: parseInt(jQuery('#ImagesPerPage').val()),
            showcounter: true,
            pager: jQuery("#pageCounter")
        });
    });

    //css the dropdown open in site editing
    jQuery('.languageChanger  li ul').css('display', 'none').css('position', 'absolute');

    window.pushDateVal = 1;  //put in rel attribute of #startdate or .numbernights field
    if (jQuery('#startdate').attr('rel') > 0) {
        window.pushDateVal = parseInt(jQuery('#startdate').attr('rel'));
    }

    if (jQuery("#startdate").length > 0) {

        if (dateFormat == "") {
            var dateFormat = "mm/dd/yyyy";
        }

        jQuery.datepicker.setDefaults({
            minDate: 0,
            buttonText: '&nbsp;&nbsp;&nbsp;',
            defaultDate: +1,
            showOn: 'both',
            buttonImageOnly: false//,
            //dateFormat: dateFormat

        });

        jQuery('#startdate').datepicker({

            onClose: function() {
                pushDate(window.pushDateVal);
            }


        });
        jQuery('#enddate').datepicker({
            beforeShow: minRange,
            defaultDate: +3
        });
    }
    if (jQuery('.languageChanger').length > 0) {
        jQuery('.languageChanger').singleDropMenu();
    }

    jQuery('.iframe_modal').live('click', function(e) {

        e.preventDefault();


        var dWidth = 800;
        var dHeight = 500;

        var $this = $(this);
        if ($this.hasClass('small')) {
            dWidth = 200;
            dHeight = 200;
        }
        if ($this.hasClass('large')) {
            dWidth = 860;
            dHeight = 600;
        }
        if ($this.hasClass('xlarge')) {
            dWidth = 930;
            dHeight = 500;
        }

        var thisDialogClass = '';
        if ($this.hasClass('noTitle')) {
            thisDialogClass = 'noTitle';
        }

        var horizontalPadding = 12;
        var verticalPadding = 0;

        theDialog = jQuery('<iframe  id="externalSite" class="externalSite" frameborder="0" src="' + this.href + '" />');
        theDialog.dialog({
            dialogClass: thisDialogClass,
            title: ($this.attr('title')) ? $this.attr('title') : 'Info',
            autoOpen: true,
            closeText: 'Close',
            width: dWidth,
            height: dHeight,
            modal: true,
            beforeclose: function() {
                $this.removeClass('disabled');
            },
            open: function(event, ui) {
                jQuery('body').css('overflow', 'hidden');
                jQuery('.ui-widget-overlay').css('width', '100%');
            },
            close: function(event, ui) { $('body').css('overflow', 'auto'); },
            closeOnEscape: false
        }).width(dWidth - horizontalPadding).height(dHeight - verticalPadding);



    });
    jQuery('.ui-widget-overlay').live('click', function() {

        // theDialog.dialog('close');

    });


    //put additional functions here.


});   //end ready

//use this to get the full size img url by removing the "tn-" prefix
function removeTn(str) {
    return str.replace(/tn-/gi, "");
}

//starts all especialsJquery's event those w/ autostart="false"
function especialsJqueryStart() {
    jQuery('.especials-jquery[autostart=false]').attr('autostart', 'true');    
    especialsJquery();
}

//new .each version - only runs those with autostart=true
function especialsJquery() {
   
    jQuery('.especials-jquery-wrap').each(function(indexOfWrap) {

        especialsJqueryElement = jQuery(this).children('.especials-jquery');%20%20%20%20%20%20%20%20if%20(especialsJqueryElement.attr('autostart') == 'true')%20{%20%20%20%20%20%20%20%20%20%20%20%20//so%20it%20doesnt%20re-start%20on%20especialsJqueryStart()%20%20%20%20%20%20%20%20%20%20%20%20especialsJqueryElement.attr('autostart', 'already-started');
            
            thisId = 'wrap-number-'+%20indexOfWrap;%20%20%20%20%20%20%20%20%20%20%20%20jQuery(this).attr('id',%20thisId);%20%20%20%20%20%20%20%20%20%20%20%20var%20url%20=%20especialsJqueryElement.attr('url');%20%20%20%20%20%20%20%20%20%20%20%20var%20especialsCategory%20=%20especialsJqueryElement.attr('especialsCategory');
            url = url + "&EventCatId=" + especialsCategory
            $.ajax({
                url: url,
                dataType: 'jsonp',
                //give callback indexed instead of random for easier url caching      
                jsonpCallback: "callbackNo" + indexOfWrap,
                invokedata: {
                    thisIdHash: '#'+%20thisId,%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20indexOfWrap:%20indexOfWrap,%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20fx:%20especialsJqueryElement.attr('fx'),%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20makeEntireDivClickable:%20especialsJqueryElement.attr('makeEntireDivClickable'),%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20secondsOfLoop:%20parseInt(especialsJqueryElement.attr('secondsOfLoop'))%20*%201000,%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pagerHasNumbers:%20especialsJqueryElement.attr('pagerHasNumbers')
                },
                error: function() {
                    logMe('error occurred in ajax request:  ' + url);
                },
                complete: function() {

                    //the pager sometimes double-calls-fills
                    jQuery(this.invokedata.thisIdHash + ' .especials-pager').html(' ');

                    //logMe(this.invokedata.thisIdHash);
                    // logMe('amount of slides' + jQuery(this.invokedata.thisIdHash + ' .especials-jquery').length);
                    jQuery(this.invokedata.thisIdHash + ' .especials-jquery').cycle({
                        fx: this.invokedata.fx,
                        timeout: this.invokedata.secondsOfLoop,
                        delay: -1000,
                        pause: true,
                        allowPagerClickBubble: true,
                        pager: this.invokedata.thisIdHash + ' .especials-pager'

                    });

                    //needed to add option since couldn't css hide them
                    if (this.invokedata.pagerHasNumbers == 'false') {
                        jQuery(this.invokedata.thisIdHash + ' .especials-pager a').text('');
                    }

                    //make div clickable and cursor
                    if (this.invokedata.makeEntireDivClickable == 'true') {
                        logMe('true');
                        jQuery(this.invokedata.thisIdHash + ' .especials-template-clone').css('cursor', 'pointer');
                        jQuery(this.invokedata.thisIdHash + ' .especials-template-clone').live('click', function() {
                            var ThisMoreDetailsLink = jQuery(this).attr('moredetailslink');
                            window.location = ThisMoreDetailsLink;
                        });
                    }

                    //clean up template - make sure there is at least 2!
                    jQuery(this.invokedata.thisIdHash + " .especials-template").hide();

                },
                success: function(data) {

                    var thisIdHashSuccess = this.invokedata.thisIdHash;
                    var indexOfWrapSuccess = this.invokedata.indexOfWrap;
                    var fxSuccess = this.invokedata.fx;
                    var secondsOfLoopSuccess = this.invokedata.secondsOfLoop;

                    jQuery.each(data, function(indexOfData, item) {

                        cloneId = "template-no-index-wrap-" + indexOfWrapSuccess + "-index-in-" + indexOfData

                        jQuery(thisIdHashSuccess).children(".especials-template").clone().attr("id", cloneId).appendTo(thisIdHashSuccess + ' .especials-jquery');

                        jQuery('#' + cloneId).removeClass('especials-template').addClass('especials-template-clone');
                        jQuery('#' + cloneId + ' .WidgetTitle').html(item.WidgetTitle);
                        jQuery('#' + cloneId + ' .WidgetText').html(item.WidgetText);
                        jQuery('#' + cloneId + ' .ThumbnailImage').attr('src', item.ThumbnailImage);

                        //large image if in template
                        jQuery('#' + cloneId + ' .LargeImage').attr('src', removeTn(item.ThumbnailImage));
                        
                        //removes MoreDetailsLink if hasPackageLongDesc == false
                        if (!item.hasPackageLongDesc) {
                            jQuery('#' + cloneId + ' .MoreDetailsLink').css('display', 'none').addClass('hidden-bc-hasPackageLongDesc-false');
                        }
                        jQuery('#' + cloneId + ' .MoreDetailsLink').attr('href', item.MoreDetailsLink);

                        //put link url in divs attr in case there is no link and entiredivclickable
                        jQuery('#' + cloneId).attr('MoreDetailsLink', item.MoreDetailsLink);

                    });  //end each data
                }
            });
            //end success ajax


        }
    });           //end each wrap div

}

//pushes the endDate back to +2d of startdate
function pushDate(numberDaysAhead) {
    if (jQuery("#enddate").length > 0) {

        var startDate = jQuery("#startdate").datepicker("getDate");
        var endDate = jQuery("#enddate").datepicker("getDate");

        if (startDate > endDate) {
            startDate.setDate(startDate.getDate() + numberDaysAhead);
            jQuery('#enddate').datepicker('setDate', startDate);
            //alert('start gt end');
        } else {
            //alert('start lt end');
        }
    }
}

//customize mindate so that enddate cannot be b4 startdate
function minRange(input) {
    return {
        minDate: (jQuery("#startdate").datepicker("getDate") != null ? jQuery("#startdate").datepicker("getDate") : 2)
    };
}
//startdate cannot be after enddate
function maxRange(input) {
    return {
        maxDate: (jQuery("#enddate").datepicker("getDate") != null ? jQuery("#enddate").datepicker("getDate") : null)
    };
}

function getCalOptions() {

    calOptions = {
        header: {
            left: 'prev,next today ',
            center: 'title',
            right: ' month,basicWeek,basicDay'
        },
        theme: true,
        timeFormat: 'h(:mm)tt',
        events: getEventsPage(),
        eventClick: function(event) {
            // opens events in a popup window

            var dHeight = 350;
            var dWidth = 640;
            var horizontalPadding = 30;
            var verticalPadding = 30;

            cal_modal = jQuery('<iframe  id="externalSite" class="externalSite" frameborder="0" src="' + event.url + '" />');

            cal_modal.dialog({
                title: event.title,
                autoOpen: true,
                width: dWidth,
                height: dHeight,
                modal: true,
                closeOnEscape: false
            }).width(dWidth - horizontalPadding).height(dHeight - verticalPadding);

            return false;
        },
        loading: function(bool) {
            if (bool) {
                jQuery('#loading').show();
            } else {
                jQuery('#loading').hide();
            }
        }
    }

    return calOptions;
}

function getLegendUrl() {
    return '../_ecalendar/dynamiclegend.asp.htm';
}

function insertLegendButtonAfterHeaderButton(name) {

    buttonToPutAfter = jQuery('.fc-button-' + name);
    nextTd = buttonToPutAfter.parent().next();

    nextTd.addClass('nextTd').attr('align', 'right');

    legendButton = buttonToPutAfter.clone();
    legendButton.addClass('fc-legend-button').addClass('fc-no-left').addClass('ui-no-left');
    legendButton.removeClass('.fc-button-' + name).removeClass('fc-state-disabled').removeClass('ui-state-disabled')

    legendButton.children().children().text('legend');

    nextTd.append(legendButton);
    jQuery('.nextTd .fc-header-space').remove();
    jQuery('.fc-legend-button').live('click', function() {
        modal(getLegendUrl(), 'Legend', 600, 400);
    });
}

function getEventsPage() {
    window.eventsPage = jQuery('#calendar').attr('title');
    //remove title so it doesnt show in tooltips
    jQuery('#calendar').attr('title', '');
    return window.eventsPage
}

function modal(url, dTitle, dWidth, dHeight) {

    iframeDialog = jQuery('<iframe  id="externalSite" class="externalSite" frameborder="0" name="eg" src="' + url + '" />');

    var horizontalPadding = 30;
    var verticalPadding = 30;

    iframeDialog.dialog({
        title: dTitle,
        autoOpen: true,
        width: dWidth,
        height: dHeight,
        modal: true,
        closeOnEscape: false
    }).width(dWidth - horizontalPadding).height(dHeight - verticalPadding);

}


//this shows in firebug or ies console if active
function logMe(str) {
    if (window.console && window.console.log) {
        window.console.log(str);
    }
}					
