/**
 * Namespaced object. Encapsulating private methods, exposing these 
 * as public via an object proxy. 
 *
 * @author 		Zone
 * @email		info@zonecontent.com
 * @url 		http://www.zonecontent.com/
 * @copyright 	Copyright (c) 2009, zonecontent.com. All rights reserved.
 * @version		1.0
 */
var rayban = window.rayban = {};
rayban.rooms = function($) {

    // Private methods

    function formatTweetResults(tweet) {
        return (
			'<li>\
				<span class="tweet-text">' + tweet.text + '</span> <span class="tweet-info">from ' + '<a href="http://www.twitter.com/' + tweet.from_user + '">' + tweet.from_user + '</a></span>\
			</li>'
		);
    }

    function getTweets(phrase, username, callback) {

        // http://apiwiki.twitter.com/Search+API+Documentation
        var api = 'http://search.twitter.com/search.json?rpp=4&callback=rayban.rooms.' + callback + '&lang=en&';

        // Construct API call
        if (phrase) {
            api += 'q=' + phrase;
        } else if (username) {
            api += 'q=from%3A' + username;
        }

        try {
            $("body").append('<script type="text/javascript" src="' + api + '"></script>');
        } catch (e) {
            // Nuffin, init
        }
    }

    function rgbToHex(rgb) {

        //Rich HACK
        //IE doesn't like this, so try catch for now...
        try {
            var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            delete (parts[0]);
            for (var i = 1; i <= 3; ++i) {
                parts[i] = parseInt(parts[i]).toString(16);
                if (parts[i].length == 1) parts[i] = '0' + parts[i];
            }
            //alert(parts.join(''));
            return (parts.join(''));

        } catch (e) {
            // Nuffin, init
        }
    }


    // Public methods

    return {

        /**
        * Global init methods
        *
        */
        init: function() {
            //Null
        },


        addColorizeProductInfo: function() {
            var viewer = $("#colorize-viewer");

            $("#collections-2009 a.thumbnail").click(function() {
                var el = $(this);
                viewer.find("img.hero").attr("src", el.find("img").attr("src").replace("192x129", "603x359"));
                viewer.find(".content").html(
					'<img src="/rooms/img/common/colorize_logo.png" alt="" id="colorize-logo" width="90" height="68" /><h4>' + el.parent().children("p").children("span").text() + '</h4>' + el.parent().find(".info").html()
				);
                return (false);
            });

            $("#collections-2009 p[class*=number] a").click(function() {
                $(this).parent().parent().find(".thumbnail").click();
                return (false);
            });

        },

        /**
        * Retrieves all tweets associated with a specific search term
        * @param	String
        */
        getFestivalTweets: function(festivalName) {
            getTweets(festivalName, null, "twitterFestivalCallback");
        },

        /**
        * Callback method for general Twitter search call
        * @param	JSON object
        */
        twitterFestivalCallback: function(data) {
            if (data) {
                var root = $("#live-tweets ol");
                var i = 0;
                var tweet;
                root.empty();
                while (tweet = data.results[i++]) {
                    root.append(formatTweetResults(tweet));
                }

            }
        },

        /**
        * Get all the tweets from the Ray Ban Twitter account  
        * 
        */
        getRayBanTweets: function() {
            // CHANGE THE USERNAME ONCE THE RAY BAN TWITTER ACCOUNT IS SETUP
            getTweets(null, "raybanrooms", "twitterRayBanCallback");
        },

        /**
        * Callback method for RayBan Twitter account call
        * @param	JSON object
        */
        twitterRayBanCallback: function(data) {
            if (data) {
                var root = $("#room-tweets ol");
                var i = 0;
                var tweet;
                root.empty();
                
                while (tweet = data.results[i++]) {
                    root.append(formatTweetResults(tweet));
                }

            }
        },


        /**
        * Retrieves the hash value from the passed URL
        * @return	String | Boolean
        */
        getHash: function() {

            if (window.location.hash && window.location.hash.length) {
                return (
					String(window.location.hash).split("#")[1]
				);
            }
            return (false);

        },

        /**
        * Embeds the Vimeo player, with custom sizing and colouring
        * @param	String (Vimeo video ID number)
        */
        embedVimeoPlayer: function(vimeoId) {

            $('html').animate({ scrollTop: 0 }, 'slow');

            var player = $(".vimeo");
            player.empty();

            var color = rgbToHex($("h1").css("color"));

            player.append('<object width="603" height="347"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + vimeoId + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=' + color + '&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=' + vimeoId + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=' + color + '&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="603" height="349"></embed></object>')

        },




        /**
        * Applies static logic to video links on balcony session page
        * 
        */
        setVideoLinks: function() {

            $(".thumbnail-list .thumbnail, .thumbnail-list .title").click(function() {

                rayban.rooms.embedVimeoPlayer(
					$(this).attr("href").split("http://vimeo.com/")[1]
				);

                return (false);
            });


        },

        /**
        * Inserts slideshow into pre-defined DOM slot
        * @param	String	path to JSON document containing all image data (i.e. /rooms/json/homepage.json)
        */
        addSlideshow: function(jsonURL) {

            var root = $("#slideshow"),
					image = root.find("#slideshow-inner img"),
					link = image.parent(),
					title = root.find(".content h1"),
					desc = root.find(".content p"),
					links = root.find(".content ul"),
					cache = null,
					timer = null;

            $.getJSON(jsonURL, onJSONLoaded);

            function nextImage() {
                root.find("li.active").next().find("a").click();
            }

            function onJSONLoaded(data) {

                if (data.length) {
                    cache = data;
                    root.addClass("js");
                    root.append(
						'<div id="slideshow-slides">\
							<ol></ol>\
						</div>'
					);

                    var slides = root.find("#slideshow-slides ol");
                    for (var i = 0; i < 6; i++) { // Max limit is SIX
                        var item = data[i];
                        slides.append(
							'<li style="background-image:url(\'' + item.thumb + '\');"><a rel="' + i + '" href="#" class="replace"></a></li>'
						);
                    }

                    // Apply interactive logic
                    slides.find("a").click(function(event) {

                        // Reset
                        slides.find(".active").removeClass("active");

                        // Set
                        var el = $(this);
                        var item = cache[Number(el.attr("rel"))];
                        el.parent().addClass("active");

                        // Set text
                        image.attr("src", item.image);
                        link.attr("href", item.url);
                        title.text(item.title);
                        desc.text(item.desc);
                        links.empty();

                        for (var a = 0; a < item.links.length; a++) {
                            links.append('<li><a href="' + item.links[a].url + '">' + item.links[a].title + '</a></li>');
                        }

                        return (false);
                    });

                    slides.find("a:first").click();
                    timer = setInterval(nextImage, 5000);

                }

            }
        },

        /**
        * Build gallery from content within page
        *
        */
        addGalleryViewport: function() {

            function setImage(el) {

                previous_image = (!el.prev().is(":eq(0)")) ? images.find("li:last-child") : el.prev();
                previous.css("backgroundImage", "url(" + getLargeImage(previous_image) + ")");

                next_image = (!el.next().is(":last")) ? images.find("li:first-child") : el.next();
                next.css("backgroundImage", "url(" + getLargeImage(next_image) + ")");

                image.attr("src", getLargeImage(el));
                title.empty().text(el.text());

                if (current_image) {
                    current_image.removeClass("active");
                    current_image.find("> span").remove();
                }
                el.addClass("active");
                el.prepend("<span></span>");

                return (el);
            }
            function getLargeImage(el) {
                return (
					el.find("img").attr("src").replace("100x60", "474x278")
				);
            }

            // Find the inital elements to manipulate
            var gallery = $("#gallery"),
				images = gallery.find("#gallery-images"),
				current_image, next_image, previous_image;

            // Slap in some HTML
            gallery.prepend(
				'<p class="title"></p>\
				<div id="gallery-viewport">\
					<a title="Previous" href="" id="gallery-previous"></a>\
					<a id="gallery-previous-button" href=""><img src="/rooms/img/common/gallery_btn_previous.png" alt="" /></a>\
					<img id="gallery-image" src="/rooms/img/474x278/test.jpg" alt="" />\
					<a title="Next" href="" id="gallery-next"></a>\
					<a id="gallery-next-button" href=""><img src="/rooms/img/common/gallery_btn_next.png" alt="" /></a>\
				</div>'
			);

            // Fetch the newly attached buttons
            var previous = gallery.find("#gallery-previous"),
				next = gallery.find("#gallery-next"),
				previousbutton = gallery.find("#gallery-previous-button"),
				nextbutton = gallery.find("#gallery-next-button"),
				image = gallery.find("#gallery-image"),
				title = gallery.find(".title");

            // Add indiviual image logic
            images.addClass("js");
            images.find("img").each(function() {
                var el = $(this);
                el.attr("src", el.attr("src").replace("474x278", "100x60"));
            });
            images.find("img").wrap('<a href=""></a>');
            images.find("a").click(function() {
                current_image = setImage($(this).parent());
                return (false);
            });
            images.find("li:first-child a").click();

            // Next and previous buttons
            previous.click(function() {
                previous_image.find("a").click();
                return (false);
            });
            next.click(function() {
                next_image.find("a").click();
                return (false);
            });
            previousbutton.click(function() {
                previous_image.find("a").click();
                return (false);
            });
            nextbutton.click(function() {
                next_image.find("a").click();
                return (false);
            });
        },

        /**
        * Insert colorize menu and add functional logic
        *
        */
        addColorizeMenu: function() {

            var menu = $("#menu-colorize"), head = $("head");

            menu.append(
				'<p id="title-colorize" class="replace"><span>Colorize this site!</span></p>\
				<ul>\
					<li><a id="colorize-default" href=""><img src="/rooms/img/common/colorize_default.jpg" width="42" height="42" alt="Normal" /></a></li>\
					<li><a id="colorize-blue" href=""><img src="/rooms/img/common/colorize_blue.jpg" width="42" height="42" alt="Blue" /></a></li>\
					<li><a id="colorize-red" href=""><img src="/rooms/img/common/colorize_red.jpg" width="42" height="42" alt="Red" /></a></li>\
					<li><a id="colorize-green" href=""><img src="/rooms/img/common/colorize_green.jpg" width="42" height="42" alt="Green" /></a></li>\
					<li><a id="colorize-pink" href=""><img src="/rooms/img/common/colorize_pink.jpg" width="42" height="42" alt="Orange" /></a></li>\
				</ul>'
			);

            menu.find("a").click(function(event) {

                // Get current object and remove come classes
                var el = $(this);
                menu.find(".active, .next-child").removeClass("active next-child");
                el.parent().addClass("active");
                el.parent().next().addClass("next-child");

                // Enable correct stylesheet
                $('link[@rel*=style][title]').each(function(i) {
                    this.disabled = true;
                    if (this.getAttribute('title') == "css-" + el.attr("id").split("-")[1]) this.disabled = false;
                });

                // Save cookie (but only for a day)
                $.cookie("colorize", el.attr("id"), { expires: 1 });

                return (false);

            });

            // Default
            var default_color = $.cookie("colorize");
            if (default_color) {
                menu.find("#" + default_color).click();
            } else {
                menu.find("a:first").click();
            }
        }

    };

} (jQuery);