﻿jQuery(document).ready(function ($) {
    $("a[href='#']").live("click", function (e) {
        e.preventDefault();
    });

    $('a[rel*=facebox]').facebox()

    
    $('(input:text, input:textarea):not(.htmlOk)').change(function () {
        $(this).val($(this).val().replace(/[<>]/g, ''));
    });
    
    $('.stripe tr:odd').addClass('odd');
    $('.stripe tr:even').addClass('even');

    //Toggler
    $(".location").click(function () {
        $('#togg').removeClass('open');
        $("#location_dropdown").delay(125).slideToggle(125, 'swing');
    });

    $(".email-tog").click(function () {
        $("#location_dropdown").slideUp(125, 'swing');
        $('#togg').addClass('open');
    });

    $('a.normalTip').aToolTip({ fixed: false,                   // Set true to activate fixed position  
        clickIt: false,                 // set to true for click activated tooltip  
        inSpeed: 200,                   // Speed tooltip fades in  
        outSpeed: 100,                  // Speed tooltip fades out  
        tipContent: '',                 // Pass in content or it will use objects 'title' attribute  
        toolTipClass: 'defaultTheme',   // Set class name for custom theme/styles  
        xOffset: 5,                     // x position  
        yOffset: 5,                     // y position  
        onShow: null,                   // callback function that fires after atooltip has shown  
        onHide: null                    // callback function that fires after atooltip has faded out      
    });

    // Track External Link Clicks
    $("a.external").live("click", function (e) {
        e.preventDefault();
        var destUrl = $(this).attr("href").split('://', 2)[1];
        _gaq.push(['_trackEvent', 'external', destUrl]);
        window.open('http://' + destUrl);
    });

    $("a.ad").live("click", function () {
        var destUrl = $(this).attr("href").split('://', 2)[1];
        _gaq.push(['_trackEvent', 'advertisement', destUrl]);
    });
})

function onLocationChanged(isFound) {
    if (isFound) {
        $(".location").trigger("click").text("Loading...");
        window.location.href = '/';
    } else {
        $('#chooseLocation .msg').hide();
        $('#chooseLocation .field-validation-error').show();
        $('#location_dropdown input').removeAttr('disabled');
    }
};

$('a.faceboxClose').live("click", function (e) {
    $.facebox.close();
});

var koddlerPage = (function () {
    var initMemberDetails = function () {
        $("#memSubtabs").tabs();
        /*
        $('#updateTrust').submit(function () {
        $(this).ajaxSubmit({
        dataType: 'json',
        success: function (data) {
        if (data.success == true) {
        jQuery(document).trigger('close.facebox');
        }
        else {
        alert("The form has errors");
        }
        }
        });
        return false;
        });
        */
    };
    var initHome = function () {

        $('#slider').cycle({
            fx: 'fade',
            speed: 4000,
            speedIn: 1000,
            speedOut: 1000,
            prev: '#prev',
            next: '#next',
            cleartypeNoBg: true
        });

        $("#cal").datepicker({
            onSelect: function (dateText, inst) {
                var evtC = $("#eventContainer");
                var evtTbl = $("#eventContainer table");
                evtC.addClass("loadingIndicatorLarge");
                evtTbl.empty();

                $.ajax({
                    dataType: "json",
                    type: "POST",
                    url: "/Event.aspx/Events",
                    data: {
                        latitude: koddlerGeo.userGeo().latitude,
                        longitude: koddlerGeo.userGeo().longitude,
                        radius: koddlerGeo.userGeo().radius,
                        startDate: dateText,
                        pageNum: 1,
                        pageSize: 6
                    },
                    complete: function (jqXHR, textStatus) {
                        evtC.removeClass("loadingIndicatorLarge");
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        evtTbl.empty().addClass("error gray").append("<tr><td>Ouch! Something went wrong getting events.</td></tr>");
                    },
                    success: function (data, textStatus, jqXHR) {
                        var row = 0;
                        evtTbl.empty();
                        $.each(data.data, function (idx, item) {
                            evtTbl.append("<tr><td>" + item.Date + " / <a href='" + item.Url + "'>" + item.Name + "</a></td></tr>");
                            ++row;
                        });

                        if (row == 0) {
                            evtTbl.empty().addClass("error gray").append("<tr><td>No Events for the Day.</td></tr>");
                        } else {
                            evtTbl.removeClass("error gray");
                            $('#eventContainer table tr:odd').addClass('odd');
                            $('#eventContainer table tr:even').addClass('even');
                        }
                    }
                });

            }

        });
    };
    var initResourceDetails = function () {
        $("#event_calendar_comments").tabs();

        $(".pictures").jCarouselLite({
            btnNext: ".next",
            btnPrev: ".prev",
            circular: false
        });
        $('.pictures li a').lightBox();
    }; 
    
    return {
        initMemberDetails: initMemberDetails,
        initHome: initHome,
        initResourceDetails: initResourceDetails
    };
}());

var koddlerGeo = (function () {
    //"use strict";
    var R = 3956; // miles
    var _userGeo = null;
    var userGeo = function () {
        if (_userGeo == null) {
            _userGeo = $("#pageGeo").data();
            _userGeo.latitudeRadians = radians(_userGeo.latitude);
            _userGeo.longitudeRadians = radians(_userGeo.longitude);
        };
        return _userGeo;
    };

    var radians = function (degrees) {
        return (degrees * Math.PI / 180);
    };

    var distance = function (lat1, lon1, lat2, lon2) {
        return Math.round(Math.acos(Math.sin(lat1) * Math.sin(lat2) +
                  Math.cos(lat1) * Math.cos(lat2) *
                  Math.cos(lon2 - lon1)) * R);
    };

    var distanceFromUser = function (lat, lon) {
        return Math.round(Math.acos(Math.sin(userGeo().latitudeRadians) * Math.sin(radians(lat)) +
                  Math.cos(userGeo().latitudeRadians) * Math.cos(radians(lat)) *
                  Math.cos(radians(lon) - userGeo().longitudeRadians)) * R);
    };

    return {
        userGeo: userGeo,
        radians: radians,
        distance: distance,
        distanceFromUser: distanceFromUser
    };
} ());

function logEvent(id, type, data) {
    $.ajax({
        url: "/Tracking.aspx/LogEvent",
        type: "POST",
        data: ({
            id: id,
            type: type,
            data: data
        })
    });
}

function logAd(id, type, collateralId) {
    $.ajax({
        url: "/Tracking.aspx/LogAdEvent",
        type: "POST",
        data: ({
            id: id,
            type: type,
            collateralId: collateralId
        })
    });
}

function DeleteThumb(ask, resourceId) {
    if (ask == false || confirm('Are you sure you want to delete the image?')) {

        $.post('/Image.aspx/Delete/' + resourceId + '?type=0',
                                function (data) {
                                    if (!data.success)
                                        alert("Failed:" + data.message);
                                    window.location = window.location;
                                    //$("#location_picture").load(window.location + " #location_picture", null, null);
                                }, "json");
    }
}
