﻿$(function () {

    // Contact AJAX submission
    $("#contact form#hello").submit(function () {
        error = false;
        var dataStringSerialized = $("form#hello").serialize();
        $("form#hello fieldset input[type=text], form#hello fieldset input[type=email], form#hello fieldset input[type=number], form#hello textarea").each(function () {
            var value = $(this).val();
            var placeHolder = $(this).attr("placeholder");
            if (value == "" || value == placeHolder) {
                $(this).addClass("error");
                error = true;
            }
            else {
                $(this).removeClass("error");
            }
        });
        if (error != true) {
            $.ajax({
                type: "POST",
                url: "contact/thanks",
                data: dataStringSerialized,
                success: function () {
                    $("form#hello fieldset").fadeOut("slow", function () {
                        $("form#hello").append("<p>Thank you for your enquiry, we'll be in touch as soon as possible.</p>");
                        pageTracker._trackPageview('/contact/thanks');
                    });
                }
            });
        }
        return false;
    });

    // Contact close function
    $("#contact a.close").click(function () {
        $("#contact").slideToggle();
    });

    // Append map and stripes to contact
    $("#contact").append("<div id='map'></div><div class='stripes' id='left'></div><div class='stripes' id='right'></div>");
    mapStrips();

    // On resize, resize stripes
    $(window).resize(function () {
        mapStrips();
    });

    // Contact stripes function
    function mapStrips() {
        var outerWidth = $(window).width() - 1024;
        var stripesWidth = outerWidth / 2;
        $("section#contact .stripes").width(stripesWidth);
    }

    // Contact open function
    $("nav[role=navigation] ul li a").click(function () {
        var target = $(this).attr("href");
        if (target == "/contact") {
            $("#contact").slideToggle("20000", function () {
                if ($.browser.SafariMobile || $.browser.webkit) {
                    $("#contact").addClass("fallback");
                    $("#map").hide();
                }
                else {
                    initialize();
                }
                mapStrips();
            });
            return false;
        }
    });

    // Navigation effects
    $("nav[role=navigation] > ul").lavaLamp({ fx: "backout", speed: 700 });
    $("nav[role=navigation] ul li:has(ul)").hoverIntent(function () {
        $(this).children("ul").hide();
        $(this).children("ul").slideDown();
    }, function () {
        $(this).children("ul").hide();
    });

    // Header twitter bird
    $("header[role=banner]").append("");
    var oldTweetId = 0;
    var username = "creativejar";

    checkStream();
    setInterval(checkStream, 2000);

    function checkStream() {
        $.getJSON('/Tweets/GetLatestTweet', function (tweets) {
            if (tweets[0].ID != oldTweetId) {
                // new tweets
                if ($("#twitter a.tweet").size() > 0) {
                    $("#twitter a.tweet").addClass("old").animate({ "bottom": "100%", "opacity": "0" }, 800, function () {
                        $("#twitter").append('<a class="tweet" data-tweet="' + tweets[0].TweetText + '" href="http://twitter.com/' + username + '/status/' + tweets[0].TweetID + '" target="_blank">Tweet</a>');
                        $("#twitter a.tweet").fadeIn("400").hover(function () {
                            var tweetContent = $(this).attr("data-tweet");
                            $(this).addClass("open").html(tweetContent);
                        }, function () {
                            $(this).removeClass("open").html("Tweet");
                        });
                    });
                }
                else {
                    $("#twitter").append('<a class="tweet" data-tweet="' + tweets[0].TweetText + '" href="http://twitter.com/' + username + '/status/' + tweets[0].TweetID + '" target="_blank">Tweet</a>');
                    $("#twitter a.tweet").fadeIn("400").hover(function () {
                        var tweetContent = $(this).attr("data-tweet");
                        $(this).addClass("open").html(tweetContent);
                    }, function () {
                        $(this).removeClass("open").html("Tweet");
                    });
                }
                oldTweetId = tweets[0].ID;
            }
        });
    }

    // Header twitter bird animation
    var birdAnimations = new Array(
           
    );

    birdAnimationRunning = false;

    $('body').append('<div id="preload"></div>');

    $.each(birdAnimations, function () {
        $("#preload").append("<img src='/UI/Images/TwitterBird/" + this[0] + "' />");
    });

    setInterval(function () {
        if (!birdAnimationRunning) {
            var animation = Math.floor(Math.random() * birdAnimations.length);
            birdAnimation(birdAnimations[animation][0], birdAnimations[animation][1]);
        }
    }, 10000);

    function birdAnimation(imageName, frames) {
        var currentFrame = 1,
        targetBird = $("#twitter a.bird"),
        dimensionWidth = $(targetBird).width();
        birdAnimationRunning = true;
        $(targetBird).css({ "background": "url('/UI/Images/TwitterBird/" + imageName + "') no-repeat" });
        setInterval(function () {
            if (currentFrame < frames) {
                $(targetBird).css({ "background-position": "-" + ((dimensionWidth + 1) * currentFrame) + "px 0px" });
                currentFrame++;
            }
            else {
                birdAnimationRunning = false;
            }
        }, 41);
    }

    // Work Carousel
    $("div#work").cjCarousel({
        btnNextClass: "next",
        btnPrevClass: "prev",
        visible: 4
    });

    // Cross browser fall-backs
    if (!Modernizr.input.placeholder) {
        $("input, textarea").each(function () {
            if ($(this).val() == "" && $(this).attr("placeholder") != "") {
                $(this).val($(this).attr("placeholder"));
                $(this).focus(function () {
                    if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
                });
                $(this).blur(function () {
                    if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
                });
            }
        });
    }

    if ($.browser.msie) {
        $(".content-template article .content").columnize({ columns: 2 });
        $("#work-detail #brief").columnize({ columns: 3, target: "#work-detail #brief" });
        $("#work-detail #what").columnize({ columns: 3, target: "#work-detail #what" });
    }

    if ($.browser.msie && parseInt($.browser.version, 10) == "7") {
        $("#wrapper").prepend("<div id='wrapper-before'></div>");
        $("#wrapper").append("<div id='wrapper-after'></div>");
    }

    // Equal heights on content template
    if ($("section[role=main]:not(#articles)").hasClass("content-template") && $("section[role=main] > aside").size() > 0) {
        var articleHeight = $(".content-template > article").height();
        var asideHeight = $(".content-template > aside").height();
        var highestCol = Math.max(articleHeight, asideHeight);
        var asidePadding = $(".content-template > aside").css("padding-top").replace("px", "");
        $(".content-template > article").height(highestCol);
        if (asideHeight > articleHeight) {
            $(".content-template > aside").height(highestCol);
        }
        else {
            $(".content-template > aside").height(highestCol - asidePadding);
        }
    }

    // Disabling text selection on elements with .no-select
    $(function () {
        $.extend($.fn.disableTextSelect = function () {
            return this.each(function () {
                if ($.browser.mozilla) {//Firefox
                    $(this).css('MozUserSelect', 'none');
                } else if ($.browser.msie) {//IE
                    $(this).bind('selectstart', function () { return false; });
                } else {//Opera, etc.
                    $(this).mousedown(function () { return false; });
                }
            });
        });
        $('.no-select').disableTextSelect(); //No text selection on elements with a class of 'noSelect'
    });

    // Fallback contact form validation
    $("#contact-fallback form").submit(function () {
        error = false;
        var dataStringSerialized = $("form#hello").serialize();
        $("#contact-fallback form input[type=text], #contact-fallback form input[type=email], #contact-fallback form input[type=number], #contact-fallback form textarea").each(function () {
            var value = $(this).val();
            var placeHolder = $(this).attr("placeholder");
            if (value == "" || value == placeHolder) {
                $(this).addClass("error");
                error = true;
            }
        });
        if (error == true) {
            return false;
        }
    });

    // Google Maps initializing
    function initialize() {
        var latlng = new google.maps.LatLng(51.477766, -0.8675017);
        var myOptions = {
            zoom: 18,
            center: latlng,
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"),
        myOptions);
        var iconlatlng = new google.maps.LatLng(51.477466, -0.8683717);
        var icon = '/UI/Images/MapIcon.png';
        var customMarker = new google.maps.Marker({
            position: iconlatlng,
            map: map,
            icon: icon
        });

        var myOptions = {
            boxClass: "info",
            alignBottom: true,
            content: '<div>' +
            '<p>Creative Jar<br />' +
            '24 High Street<br />' +
            'Twyford<br />' +
            'Berkshire<br />' +
            'RG10 9AG</p>' +
            '<ul>' +
            '<li><a href="http://maps.google.co.uk/maps?q=24%20High%20Street%2C%20Twyford%2C%20Reading%20RG10%209AG%20%28Creative%20Jar%29&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&ie=UTF-8&sa=N&hl=en&tab=wl">Get Directions</a></li>' +
            '</ul>' +
            '</div>',
            pixelOffset: new google.maps.Size(-140, 1),
            closeBoxMargin: "10px",
            closeBoxURL: "/UI/Images/ContactInfoClose.png"
        };

        var ib = new InfoBox(myOptions);
        ib.open(map, customMarker);
    }
});

jQuery.extend(jQuery.browser, { SafariMobile: navigator.userAgent.toLowerCase().match(/iP(hone|ad)/i) });
