﻿
/*--  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,
                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;
        });
    }

    // Dialog add to planner
    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', $(this).attr('title'));
            $('#dateModalDialog').dialog('open');
            $('#closeDateSelector').live("click", function () { $('#dateModalDialog').dialog('close'); });
            $('#cancelLogon').live("click", function () { $('#dateModalDialog').dialog('close'); });
            if ($('#hidLogged').length == 0) {
                //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) {
                        $('#dateModalContent').html(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>");
                    }
                });
            }

            return false;
        });

        //Logon dialog
        $("#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', $(this).attr('title'));
                $('#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;
            });
        }
    }

    $(".DateSelector").live("click", function () {

        $.ajax({
            type: "GET",
            url: "/Planner/AddDateToPlanner",
            data: "dateId=" + $(this).val() + "&toAdd=" + $(this).is(':checked') + "&date=" + $(this).closest(".rowItem").find(":hidden:first").val(),
            dataType: "html",
            cache: false,
            success: function (msg) {
                //nothing
            },
            error: function () {
                alert('An error has occured. Please refresh the page and try again.');
                console.log('CE');
            }
        });
    });

    //calendar bin delete
    $(".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>");
            }
        });

    });

    //calendar cell click
    $('.cellwrapper').click(function () {
        //no events except october
        if ($(this).parent().attr('class') != 'otherMonth') {
            window.location = $(this).find('.calDateSelected').val();
        }
    });

    //planner listing
    $(".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 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;
        });
    }

    // Dialog share submit
    $('#shareByEmail').live("click", function () {
        $.ajax({
            type: "POST",
            url: "/planner/SharePlanner",
            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;
    });

});

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);
}

/*--  Small Calendar  --*/

function SetCalendarDate(month, year) {
    $.ajax({
        type: "GET",
        url: "/Events/SetCalendarDate",
        data: "month=" + month + "&year=" + year,
        dataType: "html",
        cache: false,
        //contentType: "application/json; charset=utf-8",
        success: function (msg) {
            $('#smallCalendarContent').html(msg);
        },
        error: function () {
            console.log('CE');
        }
    });
}


/*--  Hintify  --*/

$.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() });
}


/*--  Parent events drop down  --*/

function parentDropDown() {
    $('#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');
            }
        }
    );
}

$(document).ready(function () {

    iniWatermark();
    parentDropDown();

    CreateAutocomplete('keyword', '/Events/SearchJson');

    //$('a[rel="colorbox"]').colorbox({ maxHeight: '95%', opacity: .5 });
    $('a[rel="colorbox"]').colorbox({ maxHeight: '95%', minWidth: 400, opacity: .5 });

    //submit form on enter key press
    $('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;
        }
    });

    //$('.button-wrapper li:last').addClass('first');
    $('.button-wrapper').each(function () {
        $(this).find('li:last').addClass('first');
    });
    $('.top-navigation li:last').addClass('last');

    $('A[rel="external"]').click(function () {
        window.open($(this).attr('href'));
        return false;
    });
});


/*------    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);

    });
}


//create dialog item
function createDialog(ctrId, triggerLnkId, dialogTitle, width) {
    if ($('#' + ctrId).dialog !== null) {
        var dialogWidth = 700;
        if (width != null) {
            dialogWidth = width;
        }
        var objDialog = $('#' + ctrId);
        objDialog.dialog({
            autoOpen: false,
            width: dialogWidth,
            position: 'auto',
            modal: true,
            resizable: false,
            draggable: true,
            title: dialogTitle
        });


        // Dialog Link
        $('#' + triggerLnkId).click(function () {
            objDialog.dialog('open');
            return false;
        });
    }
}

function CreateAutocomplete(txtBoxId, searchURL) {
    var cache = {};
    var keywordObj = $("#" + txtBoxId);
    keywordObj.autocomplete({
        source: function (request, response) {
            if (cache.term == request.term && cache.content) {
                response(cache.content);
            }
            if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(cache.content, function (value) {
                    return matcher.test(value.value)
                }));
            }
            $.ajax({
                url: searchURL,
                dataType: "json",
                data: { keyword: keywordObj.val() },
                success: function (data) {
                    cache.term = request.term;
                    cache.content = data;
                    response(data);
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            //log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
        }
    });
}