﻿/********************************************/
/******** Share Planner              ********/
/********************************************/
$(function() {
    // Dialog share planner
    if ($('#shareDialog').dialog !== null) {
        $('#shareDialog').dialog({
            autoOpen: false,
            width: 580,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true
        });

        // Dialog Link
        $('.share').click(function() {

            $('#shareDialog').dialog('option', 'title', 'Share my Planner');
            $('#shareDialog').dialog('open');
            $('#cancelShare').live("click", function() { $('#shareDialog').dialog('close'); });
            $('#sendShareCalendarForm').show('fast');
            $('#shareCalendarConfirm').css('display', 'none');
            $('#SharedEmailSent').val('False');
            return false;
        });
    }

    $('#shareByEmail').live("click", function() {

        $.ajax({
            type: "POST",
            url: "/planner/ShareByEmail",
            data: $('#fshare').serialize(),
            dataType: "html",
            cache: false,
            //contentType: "application/json; charset=utf-8",
            success: function(msg) {
                $('#shareDialog').html(msg);

                if ($('#SharedEmailSent').val() == 'True') {
                    $('#sendShareCalendarForm').hide('fast');
                    $('#shareCalendarConfirm').show('fast');
                    setTimeout(function() { $('#shareDialog').dialog('close'); }, 2000);
                }

            },
            error: function() {
                alert('An error has occured. Please refresh the page and try again.');
                console.log('CE');
                //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });

        return false;
    });
});

/********************************************/
/********  Small Logon               ********/
/********************************************/

$(function() {

    $("#submitSmallLogon").live("click", function() {
        $.ajax({
            type: "POST",
            url: $('#fsmallLogon').attr('action'),
            data: $('#fsmallLogon').serialize(),
            dataType: "html",
            cache: false,
            //contentType: "application/json; charset=utf-8",
            success: function(msg) {
                $('#dateModalContent').html(msg);
                $('#logonModalContent').html(msg);
                return false;
            },
            error: function() {
                alert('An error has occured. Please refresh the page and try again.');
                console.log('CE');
                //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });

        return false;

    });


    if ($('#logonModalDialog').dialog !== null) {
        $('#logonModalDialog').dialog({
            autoOpen: false,
            width: 500,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true
        });

        // Dialog Link
        $('.logonBtn').click(function() {

            $('#logonModalDialog').dialog('option', 'title', 'Open My Vivacity Planner');
            $('#logonModalDialog').dialog('option', 'EventId', $(this).attr('title'));
            $('#logonModalDialog').dialog('open');
            $('#closeDateSelector').live("click", function() { $('#logonModalDialog').dialog('close'); });
            $('#cancelLogon').live("click", function() { $('#logonModalDialog').dialog('close'); });

            return false;
        });
    }


});

/********************************************/
/********        Planner  Listing     ********/
/********************************************/
$(function() {

    $(".cal-bin").click(function() {

        $('.cellwrapper').unbind("click");

        $(this).closest(".calEvt").animate({ opacity: "hide" }, "slow");
        $(this).closest(".calEvt").animate({ opacity: "hide" }, "slow");

        $.ajax({
            type: "GET",
            url: "/planner/DeletePlannedEvent",
            data: "toto=" + $(this).attr("rel") + "&foo=true",
            dataType: "html",
            cache: false,
            //contentType: "application/json; charset=utf-8",
            success: function(msg) {
                $('.cellwrapper').click(function() {
                    window.location = $(this).find('.calDateSelected').val();
                });
            },
            error: function() {
                alert('An error has occured. Please refresh the page and try again.');
                console.log('CE');
                //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });

    });

    $('.cellwrapper').click(function() {
        //no events except october
        if ($(this).parent().attr('class') != 'otherMonth') {
            window.location = $(this).find('.calDateSelected').val();
        }
    });

    $(".btn-delete").click(function() {

        $(this).closest(".eventDetail").animate({ opacity: "hide" }, "slow");
        $(this).closest(".eventDetail").animate({ opacity: "hide" }, "slow");

        $.ajax({
            type: "GET",
            url: "/planner/DeletePlannedEvent",
            data: "toto=" + $(this).attr("rel") + "&foo=true",
            dataType: "html",
            cache: false,
            //contentType: "application/json; charset=utf-8",
            success: function(msg) {
            },
            error: function() {
                alert('An error has occured. Please refresh the page and try again.');
                console.log('CE');
                //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });

    });

    // Dialog map
    if ($('#dateModalDialog').dialog !== null) {
        $('#dateModalDialog').dialog({
            autoOpen: false,
            width: 500,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true
        });

        // Dialog Link
        $('.openDateSelectorDialog').click(function() {

            $('#dateModalDialog').dialog('option', 'title', 'Add to My Vivacity Planner');
            $('#dateModalDialog').dialog('option', 'EventId', $(this).attr('title'));
            $('#dateModalDialog').dialog('open');
            $('#closeDateSelector').live("click", function() { $('#dateModalDialog').dialog('close'); });
            $('#cancelLogon').live("click", function() { $('#dateModalDialog').dialog('close'); });
            $('#dateModalDialog').dialog('option', 'title', 'Open My Vivacity Planner');
            if ($('#hidLogged').length == 0) {
                $('#dateModalDialog').dialog('option', 'title', 'Add to My Vivacity Planner');
                //Retrieve the date for this event
                $('#dateModalContent').html('Loading dates...');

                $.ajax({
                    type: "GET",
                    url: "/Planner/GetDates",
                    data: "eventId=" + $(this).attr('rel'),
                    dataType: "html",
                    cache: false,
                    //contentType: "application/json; charset=utf-8",
                    success: function(msg) {

                        //console.log(msg);
                        $('#dateModalContent').html(msg);
                        //hCalendarCollection = $('.vevent');

                        //console.log('Number of Hcal found');
                        //console.log(hCalendarCollection.length);

                        //findAndParseHCalendars();
                    },
                    error: function() {
                        alert('An error has occured. Please refresh the page and try again.');
                        console.log('CE');
                        //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
                    }
                });
            }

            return false;
        });
    }

    $(".DateSelector").live("click", function() {

        $.ajax({
            type: "GET",
            url: "/Planner/AddDateToPlanner",
            data: "dateId=" + $(this).val() + "&toAdd=" + $(this).is(':checked') + "&date=" + $(this).closest(".rowItem").find(":hidden").val(),
            dataType: "html",
            cache: false,
            //contentType: "application/json; charset=utf-8",
            success: function(msg) {
            },
            error: function() {
                alert('An error has occured. Please refresh the page and try again.');
                console.log('CE');
                //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
            }
        });
    });

});

/********************************************/
/********    Add to Calendar Modal   ********/
/********************************************/

$(function() {

    // Dialog add to calendar
    if ($('#CalendarDialog').dialog !== null) {
        $('#CalendarDialog').dialog({
            autoOpen: false,
            width: 500,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true
        });

        // Dialog Link
        $('.addToCalendar').click(function() {
        var title = $(this).closest('.eventInfo').find('h3 a:eq(0)').text();
            $('#CalendarDialog').dialog('option', 'title', $(this).attr('title')+ ' : ' + title);
            $('#CalendarDialog').dialog('option', 'EventId', $(this).attr('rel'));
            $('#CalendarDialog').dialog('open');

            //Retrieve the date for this event
            $('#CalendarModalContent').html('Loading dates...');
            $.ajax({
                type: "GET",
                url: "/Planner/GetCalendarDates",
                data: "eventId=" + $(this).attr('rel'),
                dataType: "html",
                cache: false,
                //contentType: "application/json; charset=utf-8",
                success: function(msg) {

                    console.log(msg);
                    $('#CalendarModalContent').html(msg);
                    hCalendarCollection = $('.vevent');

                    console.log('Number of Hcal found');
                    console.log(hCalendarCollection.length);

                    findAndParseHCalendars();
                },
                error: function() {
                    alert('An error has occured. Please refresh the page and try again.');
                    console.log('CE');
                    //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
                }
            });
            return false;
        });
    }
});    
    

/********************************************/
/********        Ecard Modal         ********/
/********************************************/

function openEcardDialog() {
    $('#eCardDialog').dialog('open');
    $('#eCardDialog').dialog('option', 'title', 'Send an e-Card');
    $('#closeEcard').click(function() { $('#eCardDialog').dialog('close'); });
    $('#stepOne').show();
    $('#stepTwo').css('display','none');
    $('#stepThree').css('display', 'none');
    return false;
}

function AddRecipient() {
    var index = $('tr.recipient').size();
    var newRow = '<tr class="recipient">';
    newRow += $('a.addRecipient').closest('tr').prev('tr.recipient:first').html();
    newRow += '</tr>';
    
    $('a.addRecipient').closest('table').find('tr.recipient:last').after(newRow);

    $('tr.recipient:last input').each(function() {
        $(this).attr('id', RewriteIndex($(this).attr('id'), index));
        $(this).attr('name', RewriteIndex($(this).attr('name'), index));
        $(this).val('');
    });

    $('.relCelWrapper .remove:last').show();
}

$('.relCelWrapper .remove').live("click",(function(e) {
    $(e.target).closest('tr').remove();
    $('tr.recipient').each(function(ind) {
        $(this).find('input').each(function() {
            $(this).attr('id', RewriteIndex($(this).attr('id'), ind));
            $(this).attr('name', RewriteIndex($(this).attr('name'), ind));
       });
    });
}));

function RewriteIndex(oldValue,newIndex){
    var oldString = /\[\d\]/g;
    var newString = '[' + newIndex + ']';
    return oldValue.replace(oldString, newString);
}

$(function() {

    // Dialog map
    if ($('#eCardDialog').dialog !== null) {
        $('#eCardDialog').dialog({
            autoOpen: false,
            width: 580,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true
        });

        // Dialog Link
        $('.openEcardDialog').click(function() {
            openEcardDialog();
        });

        //refactor with toggle
        $('#eCardStepOne').click(function() {
            var isValid = false;

            $("#eCardImages input:radio").each(function() {
                if ($(this).is(':checked')) {
                    isValid = true;
                    $('#ECardImage').val($(this).closest("li").find(".hiddenEcardFile").val());
                    $('#ECardTitle').val($(this).closest("li").find(".hiddenEcardTitle").val());
                    $('#ECardDescription').val($(this).closest("li").find(".hiddenEcardDescription").val());
                    $('#Subject').val($(this).closest("li").find(".hiddenEcardDescription").val());
                }
            });

            if (isValid) {
                $('#validation').html('');
                $('#stepOne').hide('fast');
                $('#stepTwo').show('fast');
                $('#ECardSent').val('False');
                $('#stepThree').css('display', 'none');
            } else {
                $('#validation').html('<ul class="validation-summary-errors"><li>Please select an E-Card.</li></ul>');
            }
        });

        $('#eBackStepOne').click(function() {
            $('#stepTwo').hide('fast');
            $('#stepOne').show('fast');
        });

        //fecard
        $('#submitEcard').live("click", function() {

            $.ajax({
                type: "POST",
                url: "/Home/SendEcard",
                data: $('#fecard').serialize(),
                dataType: "html",
                cache: false,
                //contentType: "application/json; charset=utf-8",
                success: function(msg) {
                    $('#sendECardForm').html(msg);
                    if ($('#ECardSent').val() == 'True') {
                        $('#stepTwo').hide('fast');
                        $('#stepThree').show('fast');
                        setTimeout(function() { $('#eCardDialog').dialog('close'); }, 2000);
                    }
                },
                error: function() {
                    alert('An error has occured. Please refresh the page and try again.');
                    console.log('CE');
                    //displayError("<p>An error has occured. Please refresh the page and try again.</p>");
                }
            });

            return false;
        });
    }

});


/********************************************/
/********        Google maps         ********/
/********************************************/

$(function() {

    // Dialog map
    if ($('#mapDialog').dialog !== null) {
        $('#mapDialog').dialog({
            autoOpen: false,
            width: 700,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true
        });


        // Dialog Link
        $('.openMapDialog').click(function() {
            var address = '';
            if ($('#HiddenLocality').val() !== '') {
                address = $('#HiddenVenueName').val() + ' : ' + $('#HiddenStreetAddress').val() + ($('#HiddenStreetAddress').val() !== "" ? ", " : "") + $('#HiddenLocality').val() + " " + $('#HiddenState').val() + " " + $('#HiddenPostcode').val();
            }
            else {
                address = $('#HiddenVenueName').val() + ' : ' + $('#HiddenStreetAddress').val() + ", " + $('#HiddenState').val() + " " + $('#HiddenPostcode').val();
            }
            $('#mapDialog').dialog('option', 'title', address);
            $('#mapDialog').dialog('open');
            $('#mapDialog').dialog('option', address);
            iniGoogleMap();
            return false;
        });
    }


});

var map;
var geocoder;

function iniGoogleMap() {
    if (GBrowserIsCompatible()) {
        var latitude = $('#HiddenLatitude').val();
        var longitude = $('#HiddenLongitude').val();
        if (latitude !== '' && longitude !== '') {
            map = new GMap2(document.getElementById("map_canvas"));
            map.setUIToDefault();
            map.clearOverlays();
            //map.setMapType(G_SATELLITE_MAP);

            var venueName = $('#HiddenVenueName').val();
            var streetAddress = $('#HiddenStreetAddress').val();
            var locality = $('#HiddenLocality').val();
            var state = $('#HiddenState').val();
            var postCode = $('#HiddenPostcode').val();
            var countryName = $('#HiddenCountry').val();
            var address = '';
            if (locality !== '') {
                address = '<strong>' + venueName + '</strong><br>' + streetAddress + '<br>' + locality + ', ' + state + ', ' + postCode + '<br>' + countryName;
            }
            else {
                address = '<strong>' + venueName + '</strong><br>' + streetAddress + '<br>' + state + ', ' + postCode + '<br>' + countryName;
            }
            if ($('#HiddenVenueDescription').val() !== '') {
                address = address + '<br><br>' + $('#HiddenVenueDescription').val();
            }

            var useXml = $('#HiddenVenueId').length > 0;
            
            if (!useXml) {
                point = new GLatLng(latitude, longitude);
                marker = new GMarker(point);
                map.addOverlay(marker);
                map.setCenter(point, 15);
                createMarker(point, address);
                marker.openInfoWindowHtml(address);
            } else {

                GDownloadUrl("/Handlers/MapData.ashx?vid=" + $('#HiddenVenueId').val(), function(data) {

                    var xml = GXml.parse(data);
                    var markers = xml.documentElement.getElementsByTagName("marker");
                    var polylines = xml.documentElement.getElementsByTagName("polyline");
                    var center = xml.documentElement.getElementsByTagName("center");
                    var zoomLevel = xml.documentElement.getElementsByTagName("zoomLevel");
                    map.setCenter(new GLatLng(parseFloat(center[0].getAttribute("lat")), parseFloat(center[0].getAttribute("lon"))), parseFloat(zoomLevel[0].getAttribute("value")));

                    for (var l = 0; l < polylines.length; i++) {
                        var encodedPoints = polylines[l].getAttribute("encodedPoints");
                        var encodedLevels = polylines[l].getAttribute("encodedLevels");
                        createPolyline(encodedPoints, encodedLevels);
                    }

                    for (var i = 0; i < markers.length; i++) {
                        var info = markers[i].getAttribute("html");
                        var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon")));
                        var marker = new GMarker(point);
                        var htmlInfo = cleanInfo(info);
                        if (info !== null || info !== '') { AddMarkerInfo(marker, htmlInfo); }
                        if (i === 0) { map.openInfoWindowHtml(point, htmlInfo); }
                        map.addOverlay(marker);
                    }
                });
            }
        }
    }
}

function AddMarkerInfo(marker, info) {
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(info);
    });
}

function cleanInfo(info) {
    var reOpen = /{{/g;
    var reClose = /}}/g;
    var infoHtml = info.replace(reOpen, "<").replace(reClose, ">");
    return infoHtml;
}

function createMarker(point, address) {
    var letteredIcon = new GIcon(G_DEFAULT_ICON);
    var marker = new GMarker(point);
    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(address);
    });
    map.setCenter(point, 16);
    map.addOverlay(marker);
    return marker;
}

function createPolyline(encodedPoints, encodedLevels) {
    var encodedPolyline = new GPolyline.fromEncoded({
        color: "#E50FC4",
        weight: 5,
        points: encodedPoints,
        levels: encodedLevels,
        opacity:0.7,
        zoomFactor: 32,
        numLevels: 4
    });
    map.addOverlay(encodedPolyline);
}


/********************************************/
/********         Watermark          ********/
/********************************************/



$.fn.extend({
    hintify: function() {

        this.submit(function() {
            $("[_hint]", this).each(function() { $(this).removeHint() });
        });

        $(window).unload(function() {
            $("form [_hint]").each(function() { $(this).removeHint() });
        });

        $(":text[title],:textarea[title]", this).filter(":enabled").each(function() { $(this).hint() });

        return this;
    },
    hint: function() {
        var hintText = this.attr("title");
        if (!!hintText && (this.is(":text") || this.is(":textarea"))) {
            this.attr("_hint", hintText);
            this.addHint()
            this.focus(function() { $(this).removeHint(); });
            this.blur(function() { $(this).addHint(); });
        }
        return this;
    },
    addHint: function() {
        if ($.trim(this.val()) === "") {
            this.addClass("hinted");
            //this.removeClass("active");
            this.val(this.attr("_hint"));
        } else {
            this.addClass("active");
        }
    },
    removeHint: function() {
        if ($.trim(this.val()) === this.attr("_hint")) {
            this.val("");
            this.removeClass("hinted");
        }
        //this.addClass("active");
    }
});

function iniWatermark() {
    $("form").each(function() { $(this).hintify() });
}

/********************************************/
/********       Autocomplete         ********/
/********************************************/

function AutocompleteTitles() {
    $.ajax({
        type: "GET",
        url: "/events/AutoCompleteTitles",
        data: "q=e&limit=10",
        dataType: "json",
        cache: false,
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            var rows = new Array();
            for (var i = 0; i < data.length; i++) {
                rows[i] = data[i].Title;
            }
            $('#keywordTitle').autocomplete(rows);
        },
        error: function() {
            //Do nothing - autocomplete inactive.
        }
    });
}

/********************************************/
/********         Initialise         ********/
/********************************************/

$(document).ready(function() {
    iniWatermark();
    AutocompleteTitles();

    $('#mainEvents').click(
        function() { $('ul', this).slideToggle('fast'); }
    );

    $(document).click(
        function(e) {
            if ($(e.target).attr('class') != 'mainEvents' && $('#mainEventsList').css('display') != 'none') {
                $('#mainEventsList', this).slideToggle('fast');
            }
        }
    );

    //non flash version bg adjustments
    if ($('#flashBg').html() === '') $('#bodyTag').attr('class', 'noFlashBg');
    if ($('#bodyTag').attr('class') !== 'noFlashBg') {
        $('#flashBg').css({ height: $('#centeredContainer').height() + 'px' });
        return false;
    }
    if ($('#centeredContainer').height() > $('#bodyTag').height()) {
        $('#bodyTag').css({
            height: $('#centeredContainer').height() + 'px'
        });
    }

    //to track external links
    $('a[target*="_blank"]').click(function() {
        pageTracker._trackPageview('/outbound/' + $(this).attr('href'));
    });
    $('a[rel*="external"]').click(function() {
        pageTracker._trackPageview('/outbound/' + $(this).attr('href'));
    });

});

$('A[rel="external"]').click(function() {
    window.open($(this).attr('href'));
    return false;
});

/********************************************/
/* Forces form to submit on enter key press */
/********************************************/

$(function() {
    $('input:submit.submitButton, input:image.submitButton, input:text').keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).closest('form').submit();
            return false;
        }
    })
});

/********************************************/
/********        Subscription        ********/
/********************************************/
$(function() {

    $("button").focus(
		function() {
		    $(this).blur();
		}
	).css("cursor", "pointer");

    $("form input").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $("#subscribe").click();
            return false;
        }
    });


    $("#subscribe").click(function() {

        // Validate email address with regex
        if (!checkEmail($("#txtField").val())) {
            $('#txtField').css('background', '#ed008c');
            $('#txtField').css('color', '#ffffff');
            $('#txtField_watermark').css('background', '#ed008c');
            $('#txtField_watermark').css('color', '#ffffff');
            return false;
        }

        // Submit the form via ajax
        $.ajax({
            type: "GET",
            url: "/Home/SubscribeWidget",
            data: { email: $("#txtField").val(), name: "" },
            dataType: "html",
            error: function() {
                //

            },
            success: function(data) {
                $("div.subscription").fadeOut(100); // If successfully submitted hides the form
                $("div.thankYou").fadeIn(500);  // Shows "Thanks for subscribing" div
                return false;
            }
        });

        return false;

    });

    $('A[rel="external"]').click(function() {
        window.open($(this).attr('href'));
        return false;
    });

});

function checkEmail(email) {
    var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    //var emailVal = $("#" + email).val();
    return pattern.test(email);
}


/********************************************/
/********      Microformat           ********/
/********************************************/

///TODO : Build a proper jquery plugin

//// In case you don't have firebug...
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() { };
}

var hCalendarCollection;

$(document).ready(function() {
    hCalendarCollection = $('.vevent');

    console.log('Number of Hcal found');
    console.log(hCalendarCollection.length);

    findAndParseHCalendars();

});

function buildWindowsLiveCalendarURL(summary, dtstart, dtend, location, description) {
    if (!dtstart)
        return;
    //weird windows live doesn't like the T
    dtstart = dtstart.replace(/T/, ' ');
    dtstart = dtstart + 'Z';
    if (dtend) {
        dtend = dtend.replace(/T/, ' ');
        dtend = dtend + 'Z';
    }
    var url = "http://spaces.live.com/api.aspx?wx_action=createEvent";
    url = url + "&Wxp_name=" + summary + "&Wxp_startDateTime=" + dtstart +
        		"&Wxp_endDateTime=" + dtend + " &Wxp_location=" + location + "&Wxp_description=" +
        		description;

    return url;
}

function buildGoogleCalendarURL(summary, dtstart, dtend, location, description) {

    var url = "http://www.google.com/calendar/event?action=TEMPLATE";
    var date = dtstart;
    //google insists on an end date
    if (dtend)
        date = date + "/" + dtend;
    else
        date = date + "/" + dtstart;

    url = url + "&text=" + summary + "&dates=" + date + "&location=" + location + "&details=" + description;
    return url;
}

function AddDay(oldDate) {
    alert(oldDate);
    var temp = new Date(oldDate.substring(0, 4), oldDate.substring(4, 6) - 1, oldDate.substring(6, 8));
    temp.setDate(temp.getDate() + 1);

    var date = temp.getDate().toString();
    if (date.length == 1) date = "0" + date;

    var month = (temp.getMonth() + 1).toString();
    if (month.length == 1) month = "0" + month;

    return temp.getFullYear().toString() + month + date;
}

function buildYahooCalendarURL(summary, dtstart, dtend, location, description, uri) {

    var url = "http://calendar.yahoo.com/?v=60&type=0";
    url = url + "&title=" + summary + "&st=" + dtstart +
        		"&rend" + dtend + "&in_loc=" + location +
        		"&url=" + uri + "&DESC=" + description;
    return url;
}

function build30BoxesCalendarURL(summary, dtstart, dtend, location, description, uri) {

    var url = "http://30boxes.com/add.php?e=" + summary + " " + dtstart +
        	" " + description + " " + location;
    return url;
}

function buildiCalendarURL(dtstart_iso_nopunc, dtend_iso_nopunc, location, summary, description) {

    var url = "/home/GetICalendar?" +
			"dtstart=" + dtstart_iso_nopunc + "&dtend=" + dtend_iso_nopunc + "&location=" + location + "&summary=" + summary + "&description=" + description;
    return url;
}

//Date Helper function
function iso8601FromDate(date, punctuation) {
    var string = date.getFullYear().toString();
    if (punctuation) {
        string += "-";
    }
    string += (date.getMonth() + 1).toString().replace(/\b(\d)\b/g, '0oomph1');
    if (punctuation) {
        string += "-";
    }
    string += date.getDate().toString().replace(/\b(\d)\b/g, '0oomph1');
    if (date.time) {
        string += "T";
        string += date.getHours().toString().replace(/\b(\d)\b/g, '0oomph1');
        if (punctuation) {
            string += ":";
        }
        string += date.getMinutes().toString().replace(/\b(\d)\b/g, '0oomph1');
        if (punctuation) {
            string += ":";
        }
        string += date.getSeconds().toString().replace(/\b(\d)\b/g, '0oomph1');
        if (date.getMilliseconds() > 0) {
            if (punctuation) {
                string += ".";
            }
            string += date.getMilliseconds().toString();
        }
    }
    return string;
}


function normalizeISO8601(string, punctuation) {
    var dateArray = string.match(/(\d\d\d\d)(?:-?(\d\d)(?:-?(\d\d)(?:[T ](\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(?:([-+Z])(?:(\d\d)(?::?(\d\d))?)?)?)?)?)?/);

    var dateString;
    var tzOffset = 0;
    if (!dateArray) {
        return;
    }
    if (dateArray[1]) {
        dateString = dateArray[1];
        if (dateArray[2]) {
            if (punctuation) {
                dateString += "-";
            }

            dateString += dateArray[2];
            if (dateArray[3]) {
                if (punctuation) {
                    dateString += "-";
                }
                dateString += dateArray[3];
                if (dateArray[4]) {
                    dateString += "T" + dateArray[4];
                    if (dateArray[5]) {
                        if (punctuation) {
                            dateString += ":";
                        }
                        dateString += dateArray[5];
                    } else {
                        if (punctuation) {
                            dateString += ":";
                        }

                        dateString += "00";
                    }
                    if (dateArray[6]) {

                        if (punctuation) {
                            dateString += ":";
                        }

                        dateString += dateArray[6];
                    } else {
                        if (punctuation) {
                            dateString += ":";
                        }

                        dateString += "00";
                    }
                    if (dateArray[7]) {
                        if (punctuation) {
                            dateString += ".";
                        }


                        dateString += dateArray[7];
                    }
                    if (dateArray[8]) {
                        dateString += dateArray[8];
                        if ((dateArray[8] == "+") || (dateArray[8] == "-")) {
                            if (dateArray[9]) {
                                dateString += dateArray[9];
                                if (dateArray[10]) {
                                    dateString += dateArray[10];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return dateString;
}


function dateFromISO8601(string) {
    var dateArray = string.match(/(\d\d\d\d)(?:-?(\d\d)(?:-?(\d\d)(?:[T ](\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(?:([-+Z])(?:(\d\d)(?::?(\d\d))?)?)?)?)?)?/);

    var date = new Date(dateArray[1], 0, 1);
    date.time = false;

    if (dateArray[2]) {
        date.setMonth(dateArray[2] - 1);
    }
    if (dateArray[3]) {
        date.setDate(dateArray[3]);
    }
    if (dateArray[4]) {
        date.setHours(dateArray[4]);
        date.time = true;
        if (dateArray[5]) {
            date.setMinutes(dateArray[5]);
            if (dateArray[6]) {
                date.setSeconds(dateArray[6]);
                if (dateArray[7]) {
                    date.setMilliseconds(Number("0." + dateArray[7]) * 1000);
                }
            }
        }
    }
    if (dateArray[8]) {
        if (dateArray[8] == "-") {
            if (dateArray[9] && dateArray[10]) {
                date.setHours(date.getHours() + parseInt(dateArray[9], 10));
                date.setMinutes(date.getMinutes() + parseInt(dateArray[10], 10));
            }
        } else if (dateArray[8] == "+") {
            if (dateArray[9] && dateArray[10]) {
                date.setHours(date.getHours() - parseInt(dateArray[9], 10));
                date.setMinutes(date.getMinutes() - parseInt(dateArray[10], 10));
            }
        }
        /* at this point we have the time in gmt */
        /* convert to local if we had a Z - or + */
        if (dateArray[8]) {
            var tzOffset = date.getTimezoneOffset();
            if (tzOffset < 0) {
                date.setMinutes(date.getMinutes() + tzOffset);
            } else if (tzOffset > 0) {
                date.setMinutes(date.getMinutes() - tzOffset);
            }
        }
    }
    return date;
}

//fix relative pathed URLs
//attribution to http://www.sitepoint.com/blogs/2007/08/10/dealing-with-unqualified-href-values/
function qualifyHREF(href) {
    //get the current document location object 
    var loc = document.location;

    //build a base URI from the protocol plus host (which includes port if applicable) 
    var uri = loc.protocol + '//' + loc.host;

    //if the input path is relative-from-here 
    //just delete the ./ token to make it relative 
    if (/^(\.\/)([^\/]?)/.test(href)) {
        href = href.replace(/^(\.\/)([^\/]?)/, 'oomph2');
    }

    //if the input href is already qualified, copy it unchanged 
    if (/^([a-z]+)\:\/\//.test(href)) {
        uri = href;
    }

    //or if the input href begins with a leading slash, then it's base relative 
    //so just add the input href to the base URI 
    else if (href.substr(0, 1) == '/') {
        uri += href;
    }

    //or if it's an up-reference we need to compute the path 
    else if (/^((\.\.\/)+)([^\/].*oomph)/.test(href)) {
        //get the last part of the path, minus up-references 
        var lastpath = href.match(/^((\.\.\/)+)([^\/].*oomph)/);
        lastpath = lastpath[lastpath.length - 1];

        //count the number of up-references 
        var references = href.split('../').length - 1;

        //get the path parts and delete the last one (this page or directory) 
        var parts = loc.pathname.split('/');
        parts = parts.splice(0, parts.length - 1);

        //for each of the up-references, delete the last part of the path 
        for (var i = 0; i < references; i++) {
            parts = parts.splice(0, parts.length - 1);
        }

        //now rebuild the path 
        var path = '';
        for (i = 0; i < parts.length; i++) {
            if (parts[i] != '') {
                path += '/' + parts[i];
            }
        }
        path += '/';

        //and add the last part of the path 
        path += lastpath;

        //then add the path and input href to the base URI 
        uri += path;
    }

    //otherwise it's a relative path, 
    else {
        //calculate the path to this directory 
        path = '';
        parts = loc.pathname.split('/');
        parts = parts.splice(0, parts.length - 1);
        for (var i = 0; i < parts.length; i++) {
            if (parts[i] != '') {
                path += '/' + parts[i];
            }
        }
        path += '/';

        //then add the path and input href to the base URI 
        uri += path + href;
    }

    //return the final uri 
    return uri;
}

function findAndParseHCalendars() {
   
    var hCalendarCount = 0;
    if (hCalendarCollection.length == 0) {
        //            var vevent = oomph('<div class="iwmf_vEvent" >No Events Available</div>');
        //            oomph(vEvents).append(vevent);
        return;
    }

    hCalendarCollection.each(function() {
        var hCalendar = $(this);

        console.log($(this).html());

        var summary = hCalendar.find('.summary').text();
        if (summary.length < 1)
            summary = hCalendar.find('.summary').attr('title');
        var description = hCalendar.find('.description:first').text();
        if (description.length > 150) {
            description = description.substr(0, 147)
            description = description + "...";
            console.log(description);
        }
        else {
            console.log("No description found");
        }



        //need to deal with if the location is an hCard -- then we parse
        //differently
        var usehCardLocation = false;
        var location = hCalendar.find('.location');
        if (location.attr('class')) {
            if (location.attr('class').match(/vcard/) != null) {
                var streetaddress = hCalendar.find('.street-address').text();
                var locality = hCalendar.find('.locality').text();
                var region = hCalendar.find('.region').text();
                var postalcode = hCalendar.find('.postal-code').text();
                var countryname = hCalendar.find('.country-name').text();
                usehCardLocation = true;
            }
            else
                location = location.text();

        }
        else
            location = location.text();

        var url = hCalendar.find('.url').attr('href');
        if (url == null)
            hCalendar.find('.url>a').attr('href');
        if (url)
            url = qualifyHREF(url);


        var dtstart = hCalendar.find('.dtstart').attr('title');
        var dtend = hCalendar.find('.dtend').attr('title');
        //deal with case where it finds an attribute but there's nothing in there
        //in that case we'll make it null and the rest of the code will work
        if (dtstart) {
            if (dtstart.length == 0)
                dtstart = null;
        }
        if (dtend) {
            if (dtend.length == 0)
                dtend = null;
        }

        if (dtstart) {

            var dtstart_iso = normalizeISO8601(dtstart, true);
            var dtstart_iso_nopunc = normalizeISO8601(dtstart, false);
            var dtstart_date = dateFromISO8601(dtstart_iso);
        }
        if (dtend) {
            var dtend_iso = normalizeISO8601(dtend, true);
            var dtend_iso_nopunc = normalizeISO8601(dtend, false);
            var dtend_date = dateFromISO8601(dtend_iso);
        }

        var netbar = $('<ul class="iwmf_netBar" ></ul>');
        var iconOutlook = $('<li class="iwmf_iconOutlook"><a title="Export to Outlook" href="' + buildiCalendarURL(dtstart_iso_nopunc, dtend_iso_nopunc, encodeURIComponent(location), encodeURIComponent(summary), encodeURIComponent(description)) + '">o</a></li>');
        //var iconLive = $('<li class="iwmf_iconLive"><a target="_blank"  title="Export to Windows Live" href="' + buildWindowsLiveCalendarURL(encodeURIComponent(summary), dtstart_iso, dtend_iso, encodeURIComponent(location), encodeURIComponent(description)) + '"></a></li>');
        var iconGoogle = $('<li class="iwmf_iconGoogle"><a target="_blank" title="Export to Google"  href="' + buildGoogleCalendarURL(encodeURIComponent(summary), dtstart_iso_nopunc, dtend_iso_nopunc, encodeURIComponent(location), encodeURIComponent(description)) + '"></a></li>');
        var iconYahoo = $('<li class="iwmf_iconYahoo"><a target="_blank"  title="Export to Yahoo" href="' + buildYahooCalendarURL(encodeURIComponent(summary), dtstart_iso_nopunc, dtend_iso_nopunc, encodeURIComponent(location), encodeURIComponent(description), encodeURIComponent(url)) + '"></a></li>');
        var iconApple = $('<li class="iwmf_iconApple"><a  title="Export to Apple" href="' + buildiCalendarURL(dtstart_iso_nopunc, dtend_iso_nopunc, encodeURIComponent(location), encodeURIComponent(summary), encodeURIComponent(description)) + '"></a></li>');
        //var icon30b = $('<li class="iwmf_icon30b"><a target="_blank"  title="Export to 30 Boxes" href="' + build30BoxesCalendarURL(encodeURIComponent(summary), dtstart, dtend, encodeURIComponent(location), encodeURIComponent(description), encodeURIComponent(url)) + '"></a></li>');


        //events netbar
        $(netbar).append(iconOutlook);
        //$(netbar).append(iconLive);
        $(netbar).append(iconGoogle);
        $(netbar).append(iconYahoo);
        $(netbar).append(iconApple);
        //$(netbar).append(icon30b);

        $(this).after(netbar);

    });
}


