﻿///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 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 = "/Handlers/iCalendar.ashx?" +
			"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);

    });
}
