/* Author: 
    Stephen Griffin @ an agency called england
*/

$(document).ready(function(){
//Examples of how to assign the ColorBox event to elements
			$("a[rel='example1']").colorbox();
			$("a[rel='example2']").colorbox({transition:"fade"});
			$("a[rel='example3']").colorbox({transition:"none", width:"75%", height:"75%"});
			$("a[rel='example4']").colorbox({slideshow:true});
			$(".example5").colorbox();
			$(".example6").colorbox({iframe:true, innerWidth:425, innerHeight:344});
			$(".example7").colorbox({width:"80%", height:"80%", iframe:true});
			$(".example8").colorbox({width:"50%", inline:true, href:"#inline_example1"});
			$(".example9").colorbox({
				onOpen:function(){ alert('onOpen: colorbox is about to open'); },
				onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
				onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); },
				onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
				onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
			});
			
			//Example of preserving a JavaScript event for inline calls.
			$("#click").click(function(){ 
				$('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
				return false;
			});
    /*
     *  Large banner Case Studies carousel (homepage)
     */
    if ($("#bannerCarousel").length) $('#bannerCarousel').englandBanner({'speed':8000});
    
    /*
     *  Services pull out tab
     */ 
    if ($("#servicesTab").length && !$('body#sitemap').length) {
        
        var sT = $("#servicesTab");
        $("#servicesTab .jsButton").click(openServicesTab);
        $("#headerWrap li:first").click(openServicesTab);
        sT.find('#jsCloseLeft').css({'opacity':'0.4'}).hover(function(){
            $(this).css({'opacity':'0.8'});
        }, function(){
            $(this).css({'opacity':'0.4'});
        });

        if ($('body#home').length) {
            // bounce in (after short delay)
            sT.delay(1500).animate({
                left    : '+=70'
            }, {duration: 1000, easing: "easeOutCirc"}, function() {
                // Animation complete.
            });
        } else {
            sT.css({'left':'-1080px'});
        }

        // make the tab move when window scrolls
        $(window).bind('scrollstop', function(){
            if (sT.visible) return;

            var yPos = $(window).scrollTop()+50;
            sT.stop()
                .delay(1000)
                .css({opacity: 0.1})    // fade it so it's less annoying
                .animate({
                        top: yPos
                    }, {
                        duration:   1000,
                        easing:     "easeOutQuint",
                        complete:   function() {
                            $(this).animate({opacity:1}, 0.6);
                        }
                    }
                );
        });

        // Window resize handler
        var posWrap = $("#contentWrap");
        $(window).resize(function(e){
            if (sT.visible) sT.css({'left' : (posWrap.position().left-120)+'px'});
        });
    }
    
    function openServicesTab(e){
        e.preventDefault();
        e.target.blur();

        var offset = ($(window).width()>1200) ? ($(window).width()-1200)/2 : 0;
        var xPos = (sT.position().left >= 0) ? sT.width()*-1 : 0+offset;
        var scrollToTopSpeed = $(window).scrollTop();

        if (scrollToTopSpeed) {
            sT.animate({top:50}, {duration: scrollToTopSpeed});
            $("html, body").animate({ scrollTop : 0}, {duration: scrollToTopSpeed+200});
        }

        sT.animate({
                'left'  : xPos+'px'
            }, 300, 'swing', function(){
                // complete callback
                sT.visible = (xPos>0) ? true : false;
            }
        );
    }

    /*
     *  Services overview (homepage)
     */
    if ($("#servicesOverview").length) {

        var sOmenus = $("#servicesOverview ul.subNav li a");
        sOmenus.first().addClass('active');

        sOmenus.click(function(e){
            e.preventDefault();
            e.target.blur();

            sOmenus.each(function(){$(this).parent().removeClass('active');});  // remove active from all menus
            $(e.target).parent().addClass('active').fadeIn();

            var pos = sOmenus.index(e.target);
            $("#servicesOverview .optionsSlider").animate({
                'opacity' : 0
            }, 300, function(){
                // on complete callback
                $(this).animate({
                    'left'    : (pos*600)*-1+'px'
                    }, 60, 'swing', function(){
                        $(this).animate({'opacity':1}, 180);
                    }
                );

            });

        });
    }


    /*
     *  Footer - contact
     */
    $("#footerContact ul li a").click(function(e){
        e.preventDefault();
        e.target.blur();

        var pos = $("#footerContact ul li a").index(e.target);

        $("#footerContact ul li").each(function(){$(this).removeClass('active');})
        $(e.target).parent().addClass('active');

        $("#footerContact .optionsSlider").animate({
            'opacity' : 0
        }, 300, function(){
            // on complete callback
            $(this).animate({
                'left'    : (pos*472)*-1+'px'
                }, 60, 'swing', function(){
                    $(this).animate({'opacity':1}, 180);
                }
            );

        });
    });


    /*
     *  Recent case studies (homepage)
     */
    if ($("#recentCaseStudies .projectThumb").length) {

        $("#recentCaseStudies .moreButton").click(function(e){

            var ow = $(e.target).closest('#recentCaseStudies').find('.optionsWindow');

            if (ow.height()<600) {
                e.preventDefault();
                e.target.blur();

                ow.animate({
                    'height' : ow.height() + 206
                }, 600, function() {
                    // animation complete
                    $("html, body").animate({ scrollTop : '+=206px' }, 300);
                });
            }

            if (ow.height()>400) $(this).html("Click here to view more work...").attr({'href':'/work'});
        });
    }


    /*
     *  Twitter feed
     */
    if ($("#twitterFeed").length) {

       $.ajax({
                url             : 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=weareengland',
                dataType	: 'jsonp',
                success		: function(json){
                    for (var i=0; i<json.length; i++) {
                        var tweet = $("<div class='tweet'></div>");
                        tweet.append($(
                                        "<p>"+json[i].text.withClickableURLs()+"</p>\n\
                                         <span class='datePosted'><img src='/images/longDash.png' alt='' />&nbsp;&nbsp;"+formatDate(json[i].created_at).date+"&nbsp;&nbsp;"+"<img src='/images/longDash.png' alt='' />&nbsp;&nbsp;</span>"
                                    ));
                        $("#twitterFeed .optionsWindow").append(tweet);
                        if (i==0) tweet.fadeIn().addClass('active');
                    }
                }
        });
        // auto scroll
        window.setInterval(function(){
            var curr = $("#twitterFeed div.active");
            var nxt = (curr.next().length) ? curr.next() : $("#twitterFeed div.tweet").first();

            curr.animate({'opacity':'0'}, 600, 'swing', function(){
                $(this).hide().removeClass('active').css({'opacity':'1'});
                nxt.addClass('active').fadeIn(1);
            });
        }, 12000, 'swing', function(){

        });
    }


    /*
     *  Blog feed
     */
    if ($("#blogFeed").length) {
        $.ajax({
                url             : 'http://blog.englandagency.com/feed/?feed=json&jsonp=?',
                dataType	: 'jsonp',
                success		: function(json){
                    var latestPost = $("#blogFeed #latestPost");
                    $("h4.blogTitle", latestPost).html(json[0].title);
                    $("p.blogTeaser", latestPost).html(json[0].excerpt).find('a').html('');
                    $(".blogLinks span a", latestPost).attr('href', json[0].permalink);
                    $(".blogLinks span.dateTime", latestPost).html(json[0].date);
                    $(".blogLinks span.blogTag", latestPost).html('<a href="">'+json[0].categories[0].title+'</a>');
                    $(".blogLinks span.blogTag a", latestPost).attr('href', 'http://blog.englandagency.com/category/'+json[0].categories[0].slug);
                }
        });
    }


    /*
     *  Project thumbnails (appear on a range of pages)
     */
    if ($(".projectThumb").length) {

        $('.projectThumb h3').css({'opacity':'0.75'});

        // Title Bounce In - OPTION 1
        $('.projectThumb').hover(function(e){
            // Title
            $(this).find('h3').animate({'top':'75px'}, {duration: 400, easing:"easeOutBack"});
        }, function(e) {
            // Title
            $(this).find('h3').stop(true, true).animate({'top':'-50px'}, 200);
        });

        /* Title tracks mouse - OPTION 2
        $('.projectThumb').hover(function(e){

            $(this).find('.imageWrap img').css({'top':'-206px'});
            $(this).find('h3').css({'opacity':'0.75'});

            $(this).mousemove(function(e){
                $(this).find('h3').css({'top':e.pageY - $(this).offset().top});
            });

        }, function(e) {

            $(this).find('img').css({'top':'0'});
            $(this).find('h3').stop(true, true).animate({'opacity':'0'}, 200);
        });
        */


    }
    // hide the related work div if there are no related projects (specific service page)
    if ($("#services .projectThumb").length) $("#relatedWork").removeClass('hidden').show();



    /*
     *  Contact page
     */
    if ($("body#contact").length) {

        $("#officeChoices .optionsWindow").css({'height':'150px'});

        var allLocs = new Array();
        allLocs['kent']         = new google.maps.LatLng(51.2823, 1.0725);
        allLocs['birmingham']   = new google.maps.LatLng(52.4852, -1.9030);
        allLocs['leeds']        = new google.maps.LatLng(53.7935, -1.5569);
        
        var loc = (getUrlVars()["loc"]) ? getUrlVars()["loc"] : 'leeds';
        var pos = 0;
            switch (loc) {
                case 'leeds'        :pos=0;break;
                case 'kent'         :pos=1;break;
                case 'birmingham'   :pos=2;break;
            }

        var map = initializeMap( allLocs[loc] );
        initLocation(pos, map);

        // init map + address details
        var mapMenus = $("#officeChoices ul.subNav li a");
        mapMenus.click(function(e){
            e.preventDefault();
            e.target.blur();

            var pos = (mapMenus.index(e.target)) ? mapMenus.index(e.target) : 0;

            $("#googleMap").animate({'height':'340px'}, 1000, function(){
                // resize complete
                //map.setCenter(new google.maps.LatLng(mrkr[1]+0.0015, mrkr[2]));
            });

            map.setZoom(7);

            mapMenus.each(function(){$(this).parent().removeClass('active');});  // remove active from all menus
            $(e.target).parent().addClass('active').fadeIn();

            initLocation(pos, map);
        });
    }

});





String.prototype.withClickableURLs = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url.link(url);
	});
};



function initLocation(pos, map) {

    $("#officeChoices ul.subNav li").removeClass('active');
    $($("#officeChoices ul.subNav li")[pos]).addClass('active');

    // change address details
    $("#officeChoices .optionsSlider").animate({
        'opacity' : 0
    }, 500, function(){
        // on complete callback
        $(this).animate({
            'top'    : (pos*200)*-1+'px'
            }, 60, 'swing', function(){
                $(this).css({'opacity':1});
            }
        );

    });

    // pan the map to the selected office
    var latlng;
    switch (pos) {
        case 0:latlng = new google.maps.LatLng(53.7935, -1.5569);break;
        case 1:latlng = new google.maps.LatLng(51.2823, 1.0725);break;
        case 2:latlng = new google.maps.LatLng(52.4852, -1.9030);break;
    }
    map.panTo( latlng );

    // set location on form
    
}

        

function formatDate( date ) {

        var dateObj	= {};
        var dateRaw = new Date(date).toDateString();

        dateObj.date	= dateRaw.substr(0, dateRaw.length-5);
        dateObj.time	= new Date(date).toLocaleTimeString();

        return dateObj;
}

function initializeMap( ll ) {

    // Map
    var map = new google.maps.Map(document.getElementById("googleMap"), {
      zoom      : 7,
      center    : ll,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      mapTypeControl : false
    });

    // Markers
    var aMarkers = new Array(
        ["Leeds office", 53.7935, -1.5569, "<div class='infoWindow'><h2>Leeds office</h2><p><br />Whitehall Waterfront,<br />2 Riverside Way,<br />Leeds,<br />LS1 4EH<br /><strong>Tel: </strong>0113 234 5600 </p></div>"]
    );
    for (var i=0; i<3; i++) {
        createMarker( aMarkers[i] );
    }

    function createMarker(mrkr) {

        // Create the bubble pop up
        var infowindow = new google.maps.InfoWindow({
            content     : mrkr[3],
            maxWidth    : 100
        });
        // Add the marker
        var marker = new google.maps.Marker({
            position    : new google.maps.LatLng(mrkr[1], mrkr[2]),
            title       : mrkr[0],
            icon        : '/images/mapMarker.png'
        });
        //marker.iwindow = infowindow;
        marker.setMap(map);
        // Add event listener for this marker

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
            map.setZoom(16);
            map.setCenter(new google.maps.LatLng(mrkr[1], mrkr[2]));

            $("#officeChoices ul.subNav li a").click(function(){
               infowindow.close();
            });

            $("#googleMap").animate({'height':'600px'}, 1000, function(){
                google.maps.event.trigger(map, "resize");
                map.setCenter(new google.maps.LatLng(mrkr[1]+0.0015, mrkr[2]));
            });
        });
    }

    return map;
}




/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 *
 * http://blog.stevenlevithan.com/archives/date-time-format
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


function gotBlogPosts(json) {

    var b = $("#blogFeed");

    /*
    if (json.value.items.length) {

        //var date = dateFormat(json.value.items[0].pubDate, "d/m/yy, h:MMtt");
        var desc = json.value.items[0].description;
        var link = json.value.items[0].link;
        var title = json.value.items[0].title;

        b.find('h4.blogTitle').html(title);
        b.find('span.dateTime').html(date);
        b.find('p.blogTeaser').html(desc);
        b.find('span.viewArticle a').attr({'href':link}).html('View article');

        b.find('#latestPost').css({'background':'none'});
    } else {
        b.find('h4.blogTitle').html('Blog content is currently unavailable.').css({'text-align':'center'});
    }

    $("#latestPost").css({'background':'transparent'});
    */
}


function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}

function ReadCookie(cookieName) {
    var theCookie=""+document.cookie;
    var ind=theCookie.indexOf(cookieName);
    if (ind==-1 || cookieName=="") return "";
    var ind1=theCookie.indexOf(';',ind);
    if (ind1==-1) ind1=theCookie.length;
    return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}



