﻿var Maxxis = window.Maxxis || {};

Maxxis.Common = (function() {

    return {

}
})();

function listEvents(data) {
    alert(data);
}


function ClearAddress(){
    $("#textAddress").val("");
}

function GetDirections(title) {
    tb_show("Event Directions.", "http://maps.google.com/maps?q=" + $("#textAddress").val() + "%20to%20" + $("#hiddenLon").val() + "," + $("#hiddenLat").val()  + "&keepThis=true&TB_iframe=true&height=600&width=800", false);
}


// Event Page methods
Maxxis.Events = (function() {
    var map = {};

    function drawMap(canvas) {
        var myLatlng = new google.maps.LatLng(52.41382, -1.78402);
        var myOptions = { zoom: 6, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }
        map = new google.maps.Map(document.getElementById(canvas), myOptions);
    }

    function addEventPin(lon, lat, title) {


        var infowindow = new google.maps.InfoWindow({
            //content: '<b style="color:black;">' + title + '</b>',
        content: '<form action="javascript:GetDirections()"><div style="padding:10px;"><ul><li><span style="color:#000;font-size:15px;font-weight:bold;line-height:18px;">' + title + '</span></li><li>Enter your address:</li><li><input style="left: 0px; margin:0px; padding: 0px;" type="text" size="40" maxlength="200" name="textAddress" id="textAddress" value="Enter your address or postcode here..." onfocus="ClearAddress();" /></li><li><input type="hidden" id="hiddenLon" value="' + lon + '"/><input type="hidden" id="hiddenLat" value="' + lat + '"/><input style="left: 0px; margin: 0px; padding: 0px;margin-top:10px;" value="Get Directions" type="submit"></li></ul></div></form>',
            size: new google.maps.Size(50, 50)
        });

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lon, lat),
            map: map,
            title: title,
            icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
        });
    }





    function addEvents() {

        // Loop through event list array and add pins to map
        for (var i = 0; i < Maxxis.Events.eventList.length; i++) {

            //alert(Maxxis.Events.eventList[i].location);

            if (getCoords(Maxxis.Events.eventList[i].location)) {
                var ords = Maxxis.Events.eventList[i].location.split(",");
                addEventPin(ords[0], ords[1], Maxxis.Events.eventList[i].title);
            }
        }
    }


    function getCoords(where) {
        var re = /[a-z]/i; // Regex that checks for lon, lat values

        if (where != null) {
            if (where.match(re) == null) {
                if (where.length > 0) {
                    return where.split(",");
                }
            }
        }
        return null;
    }

    return {
        eventList: [],

        init: function(canvas) {
            /*count = feedsArray.length;
            for (var i = 0; i < count; i++) {
            new Maxxis.Events.Feed(feedsArray[i][0], feedsArray[i][1], callback);
            }
            */
            drawMap(canvas);
            addEvents();
        },

        // Formats google date -(Taken from Google)
        formatDateTimes: function(gCalTime) {

            if (!gCalTime) return;
            // text for regex matches
            var remtxt = gCalTime;

            function consume(retxt) {
                var match = remtxt.match(new RegExp('^' + retxt));
                if (match) {
                    remtxt = remtxt.substring(match[0].length);
                    return match[0];
                }
                return '';
            }

            // minutes of correction between gCalTime and GMT
            var totalCorrMins = 0;

            var year = consume('\\d{4}');
            consume('-?');
            var month = consume('\\d{2}');
            consume('-?');
            var dateMonth = consume('\\d{2}');
            var timeOrNot = consume('T');

            // if a DATE-TIME was matched in the regex 
            if (timeOrNot == 'T') {
                var hours = consume('\\d{2}');
                consume(':?');
                var mins = consume('\\d{2}');
                consume('(:\\d{2})?(\\.\\d{3})?');
                var zuluOrNot = consume('Z');

                // if time from server is not already in GMT, calculate offset
                if (zuluOrNot != 'Z') {
                    var corrPlusMinus = consume('[\\+\\-]');
                    if (corrPlusMinus != '') {
                        var corrHours = consume('\\d{2}');
                        consume(':?');
                        var corrMins = consume('\\d{2}');
                        totalCorrMins = (corrPlusMinus == '-' ? 1 : -1) * (Number(corrHours) * 60
						+ (corrMins == '' ? 0 : Number(corrMins)));
                    }
                }

                // get time since epoch and apply correction, if necessary
                // relies upon Date object to convert the GMT time to the local
                // timezone
                var originalDateEpoch = Date.UTC(year, month - 1, dateMonth, hours, mins);
                var gmtDateEpoch = originalDateEpoch + totalCorrMins * 1000 * 60;
                var ld = new Date(gmtDateEpoch);

                // date is originally in YYYY-MM-DD format
                // time is originally in a 24-hour format
                // this converts it to MM/DD hh:mm (AM|PM) 
                dateString = (ld.getMonth() + 1) + '/' + ld.getDate() + ' ' +
				((ld.getHours() > 12) ? (ld.getHours() - 12) : (ld.getHours() === 0 ? 12 :
				ld.getHours())) + ':' + ((ld.getMinutes() < 10) ? ('0' +
				ld.getMinutes()) : (ld.getMinutes())) + ' ' +
				((ld.getHours() >= 12) ? 'PM' : 'AM');
            } else {
                // if only a DATE was matched
                dateString = parseInt(month, 10) + '/' + parseInt(dateMonth, 10);
            }
            return dateString;
        },
        addClass: function(eventType) {
            var cls;

            switch (eventType) {
                case "British Superbikes":
                    cls = "red"
                    break;
                case "Isle of Man TT":
                    cls = "gold"
                    break;
                case "Max Power Live Events":
                    cls = "orange"
                    break;
                case "Motor Cross":
                    cls = "green"
                    break;
                default:
                    cls = "grey";
            }

            return cls;
        },
        generateMapLink: function(where) {
            var ords = getCoords(where)
            if (ords) {
                map.set_center(new google.maps.LatLng(ords[0], ords[1]));
                map.set_zoom(8);
            }
        },
        // Feed collection
        feeds: [],
        // Container to hold all json feeds
        combinedFeed: {
            feed: {
                entry: []
            }
        },
        // Feed object
        Feed: function Feed(feedName, feedUrl, callback) {
            var name, url;

            jsonCallback = function(data) {

                Maxxis.Events.feeds.push(data);

                if (Maxxis.Events.feeds.length == count) {
                    if (count > 1) {
                        // Combine feeds
                        for (var i = 0; i < count; i++) {
                            Maxxis.Events.combinedFeed.feed.entry = Maxxis.Events.combinedFeed.feed.entry.concat(Maxxis.Events.feeds[i].feed.entry);
                        }
                    }
                    else {
                        Maxxis.Events.combinedFeed.feed.entry = Maxxis.Events.feeds[0].feed.entry;
                    }

                    // Sort
                    Maxxis.Events.combinedFeed.feed.entry.sort(sortByDate);
                    addEventsToMap();
                    callback.call(this, Maxxis.Events.combinedFeed);
                }
            };

            this.setName = function(feedName) {
                name = feedName;
                return this;
            };
            this.getName = function() {
                return this;
            };
            this.setUrl = function(feedUrl) {
                url = feedUri.replace("{#calendarUrl}", feedUrl);
                return this;
            };
            this.getUrl = function() {
                return this;
            };

            this.fetchFeed = function() {
                $.getJSON(url, jsonCallback);
            };

            this.setName(feedName);
            this.setUrl(feedUrl);
            this.fetchFeed();
        },
        count: 0
    }
})();

Maxxis.Gallery = (function() {

    var userId = "37667639@N03"
    var setUri = "http://api.flickr.com/services/feeds/photoset.gne?set={#set}&nsid={#id}&lang=en-gb&format=json&jsoncallback=?";
    var publicUri = "http://api.flickr.com/services/feeds/photos_public.gne?id={#id}&tags=public&lang=en-gb&format=json&jsoncallback=?";
    return {
        so: {},

        init: function(flickrUserId, setId, container) {
            so = new SWFObject("/User controls/gallery/flashgallery.swf", "gallery", "100%", "480", "8");
            so.addParam("quality", "high");
            so.addParam("allowFullScreen", "true");
            so.addVariable("color_path", "/User controls/gallery/default.xml");
            Maxxis.Gallery.showPhotoSet(flickrUserId, setId, container);
            so.write(container);
        },
        getMainGallery: function() {
            var url = publicUri.replace("{#id}", userId);

            $.getJSON(url, function(data) {

                $.each(data.items, function(i, item) {
                    $("<img/>").attr("src", item.media.m.replace("_m", "")).appendTo("#mainGalleryImage");
                });

                $("#mainGalleryImage").innerfade();
            });
        },
        showPhotoSet: function(flickrUserId, setId, container) {
            so.addVariable("content_path", "http://www.flickr.com/photos/" + flickrUserId + "/sets/" + setId + "/");
            so.write(container);
        }
    }
})();

Maxxis.Video = (function() {
    return {
        ytPlayer: {},
        init: function(videoId) {
            Maxxis.Video.loadPlayer(videoId);
        },
        loadPlayer: function(videoId) {
            var params = { allowScriptAccess: "always", allowfullscreen: "true" };
            var atts = { id: "myytplayer" };
            swfobject.embedSWF("http://www.youtube.com/v/" + videoId +
                           "&enablejsapi=1&playerapiid=ytPlayer&rel=0&fs=1",
                           "videoDiv", "480", "295", "8", null, null, params, atts);
        },
        loadVideo: function(videoId) {
            if (Maxxis.Video.ytPlayer)
                Maxxis.Video.ytPlayer.loadVideoById(videoId, 0);
        },
        videoError: function(errorCode) {
            alert("An error occured of type:" + errorCode);
        }

    }
})();

function onYouTubePlayerReady(playerId) {
    Maxxis.Video.ytPlayer = $("#myytplayer").get(0);
}
