
(function ($, social) {
	var MARK = {
		siteURL: '',
		filePath: '',
		controller: '',
		action: '',
		query: '',
		lastClicked:-1,
		assets: [],
		staff: {},
	
		trackEvent: function (category, action, label, value) {
			try {
				pageTracker._trackEvent(category, action, label, value);
			} catch (e) {}
		},

		socialUrl: function ($elem) {
			var url = window.location.href;
			if ($elem) {
				var $toolbar = $elem.closest('section.social-tools'),
					deeplink = $toolbar.attr('itemtype');
				if (deeplink && deeplink.substr(0, 7) == 'http://') {
					url = deeplink;
				}
			}
			return url;
		},

		twitterMessage: function ($elem) {
			var msg = 'We are Mark. @markagency ';
			if ($elem) {
				var $title = $elem.closest('article').find('h2'),
					title = $title.text();
				if (title) {
					msg = '';
					if (MARK.controller.length) {
						msg = MARK.controller.charAt(0).toUpperCase() + MARK.controller.substr(1) + ': ';
					}
					msg += title + ' @markagency ';
				}
			}
			return msg;
		},
		
		init: function (siteURL, filePath, controller, action, query) {
			MARK.siteURL = siteURL;
			MARK.filePath = filePath;
			MARK.controller = controller;
			MARK.action = action;
			MARK.query = query;

			// Social media
			social.setOptions({
				proxyUrl: filePath + '/socialmedia/',
				gaTrackEvent: true,
				url: MARK.socialUrl,
				twitterMessage: MARK.twitterMessage
			});
			$('.social-tools a:not(.email,.print)').click(function (e) {
				e.preventDefault();
				var network = this.hash.substr(1),
					func = social[network];
				if (!(network in social) || !$.isFunction(func)) {
					alert('Invalid social network.');
					return;
				}
				func($(this));
			});

			// Facebox
			$.extend($.facebox.settings, {
				loadingImage: filePath + '/_images/clear.gif',
				closeImage: filePath + '/_images/closelabel.gif',
				opacity: 0.4
			});
			$('a[rel*=facebox]').facebox();
			$('a.close').trigger('close.facebox');

			// Email to friend
			$.ajaxSetup({cache:true});
			$('a[rel*=email]').click(function (e) {
				e.preventDefault();
				var url = $(this).attr('href') + '?url=' + encodeURIComponent(MARK.socialUrl($(this)));
				$.facebox({ajax: url});				
				MARK.trackEvent('SocialMedia', 'send to friend');
			});
			
			// We Are Mark. Who Are You? - Contact form
			if($('#contact-wrapper')){
				$("#contact-wrapper").mouseover(function(){
			      MARK.showContactForm();
			    }).mouseout(function(){
			      MARK.hideContactForm();
			    });
			}
			
			if (controller == 'work' && action == 'view') {
				this.loadGallery();
			}
			
			if (controller == 'default' && action == 'about') {
				this.loadStaff();
				$('#awards .year-items').masonry({
					singleMode: true,
					columnWidth: 260,
					gutterWidth: 100,
					itemSelector: '.awarder-item',
					resizable: false
				});
			}
		},

		showContactForm:function(){
			$('#contact-wrapper').css('height', 'auto');
			$('#contact-form').show();
			$('#contact-wrapper').find('h3 a').css('background-position', 'bottom left');
		},
		
		hideContactForm:function(){
			$('#contact-wrapper').css('height', '46px');
			$('#contact-wrapper').find('h3 a').css('background-position', 'top left');
			$('#contact-form').hide();
		},
		
		loadStaff:function(){
			var url = 'http://' + MARK.siteURL + MARK.filePath + '/staff/staff.json';
			$.ajax({
				'async': false, // synchronous request required so js does not progress until success callback fires - see http://stackoverflow.com/questions/2177548/load-json-into-variable
				'global': false,
				'url': url,
				'dataType': "json",
				'success': function (data) {
					if (data.status === 0) {
						MARK.makeStaff(data.res);
					}
				}
			});
		},

		addKeyStaff:function(id, summary){
			MARK.staff['key-' + id] = {summary: summary};
			$('#img-key-' + id).css('cursor', 'pointer').click(function () {
				MARK.showStaff('key-' + id, true);
			});
		},
		
		makeStaff:function(json){
			$.extend(MARK.staff, json);
			var staff = json,
				arr_len = staff.length,
				str = '';
			for(var i = 0; i < arr_len; i++){
				str += '<a href="javascript:void(0)" onclick="MARK.showStaff(' + i + ')"><img id="img-' + i + '" src="' + MARK.filePath + staff[i].image + '" width="70" height="70" alt="' + staff[i].firstname + '" /></a>';
			}
			if(arr_len > 0){
				$('#staff-pics').prepend(str);
			}
			$(document).click(function (e) {
				if (!$(e.target).closest('#staff-pics').length && !$(e.target).closest('.key-ppl').length) {
					MARK.showStaff(-1);
				}
			});
		},
		
		showStaff:function(i, keyperson){
			if(i != -1 && this.lastClicked != i){
				var staff = MARK.staff[i];
				$('#tooltip div div').html('&#8220;' + staff.summary + '&#8221;');
				$('#tooltip').hide();
				$('#tooltip').fadeIn("slow");
				var position = $('#img-' + i).offset(),
					topOffset = keyperson ? 80 : 35,
					leftOffset = keyperson ? 90 : 50;
				$('#tooltip').css({'top': position.top - $('#tooltip').outerHeight() + topOffset, 'left': position.left + leftOffset});
				this.lastClicked = i;
			}else{
				$('#tooltip').fadeOut("fast");
				this.lastClicked = -1;
			}
		},
		
		loadGallery:function(){
			var url = 'http://'+ MARK.siteURL + MARK.filePath +'/work/assets/' + MARK.query + '.json';
			$.ajax({
				'async': false, // synchronous request required so js does not progress until success callback fires - see http://stackoverflow.com/questions/2177548/load-json-into-variable
				'global': false,
				'url': url,
				'dataType': "json",
				'success': function (data) {
					if (data.status === 0) {
						MARK.makeGallery(data.res);
					}
				}
			});
		},
		
		makeGallery:function(json){
			$.extend(MARK.assets, json);
			var assets = json,
				arr_len = assets.length,
				str = '';
			for(var i=0; i < arr_len; i++){
				str += '<li><a href="javascript:void(0)" onclick="MARK.showGalleryItem(' + i + ')">' + (i+1) + '</a></li>';
			}
			if(arr_len > 0){
				$('#pagination').prepend(str);
				this.showGalleryItem(0);
			}
		},

		showGalleryItem:function(i){
			var $gallery = $('#img-gallery').empty().addClass('loading'),
				asset = this.assets[i],
				galWidth = $gallery.width(),
				galHeight = $gallery.height(),
				width = asset.width || galWidth,
				height = asset.height || galHeight;

			if (asset.media == 'flash') {
				$('<div id="galleryFlash"/>').appendTo($gallery);
				swfobject.embedSWF(MARK.filePath + asset.path, 'galleryFlash', width, height, '8', '', {}, {}, {}, function (args) {
					if (args.ref) {
						var $swf = $(args.ref);
						if (height < galHeight) {
							$swf.css('margin-top', galHeight / 2 - height / 2);
						}
						if (width < galWidth) {
							$swf.css('margin-left', galWidth / 2 - width / 2);
						}
					}
				});
				$gallery.removeClass('loading');
			} else {
				// Images
				var img = new Image();
				$(img).load(function(){
					var $this = $(this),
						imgHeight = this.height,
						imgWidth = this.width;
					$this.hide();
					if (imgHeight < galHeight) {
						$this.css('margin-top', galHeight / 2 - imgHeight / 2);
					}
					if (imgWidth < galWidth) {
						$this.css('margin-left', galWidth / 2 - imgWidth / 2);
					}
					$gallery.removeClass('loading').append($this);
					$this.fadeIn();
				}).attr('src', this.filePath + this.assets[i].path);
			}

			var lis = $('#pagination').find('li');
			lis.removeClass('current');
			$(lis[i]).addClass('current');
		},

		// Encoded with Enkoder: http://hivelogic.com/enkoder/form
		sydneyEmail: function(){
			var x="function f(x){var i,o=\"\",l=x.length;for(i=l-1;i>=0;i--) {try{o+=x.c" +
			"harAt(i);}catch(e){}}return o;}f(\")\\\"function f(x,y){var i,o=\\\"\\\\\\\""+
			"\\\\,l=x.length;for(i=0;i<l;i++){if(i<70)y++;y%=127;o+=String.fromCharCode(" +
			"x.charCodeAt(i)^(y++));}return o;}f(\\\"\\\\#&(8\\\\\\\\\\\"\\\\4=!y.)4+\\\\"+
			"\\\\004\\\\\\\\017\\\\\\\\013OKW\\\\\\\\014O\\\\\\\\031\\\\\\\\001\\\\\\\\0" +
			"20\\\\\\\\021D'_mcmj|e6}ivzsaZq\\\\\\\\177RI\\\\\\\\nEGG\\\\\\\\002OEn\\\\\\"+
			"\\026\\\\\\\\026LSHR%\\\\\\\\177\\\\\\\\030d\\\\\\\\024hr=)6=1,\\\\\\\\026:" +
			"9+1u?23q\\\\\\\\001\\\\\\\\024^L\\\\\\\\005[DNSYQ\\\"\\\\,70)\\\"(f};)lo,0(" +
			"rtsbus.o nruter};)i(tArahc.x=+o{)--i;0=>i;1-l=i(rof}}{)e(hctac};l=+l;x=+x{y" +
			"rt{)84=!)31/l(tAedoCrahc.x(elihw;lo=l,htgnel.x=lo,\\\"\\\"=o,i rav{)x(f noi" +
			"tcnuf\")"                                                                    ;
			while(x=eval(x));
		},
		
		melbourneEmail: function(){
			var x="function f(x){var i,o=\"\",l=x.length;for(i=l-1;i>=0;i--) {try{o+=x.c" +
			"harAt(i);}catch(e){}}return o;}f(\")\\\"function f(x,y){var i,o=\\\"\\\\\\\""+
			"\\\\,l=x.length;for(i=0;i<l;i++){if(i==79)y+=i;y%=127;o+=String.fromCharCod" +
			"e(x.charCodeAt(i)^(y++));}return o;}f(\\\"\\\\+?2'>1;\\\\\\\\\\\"\\\\y/+3/9" +
			"10wB]\\\\\\\\003C\\\\\\\\014\\\\\\\\027\\\\\\\\003\\\\\\\\001U5H\\\\\\\\006" +
			"\\\\\\\\r\\\\\\\\004\\\\\\\\002\\\\\\\\033\\\\\\\\037K\\\\\\\\037\\\\\\\\02" +
			"6\\\\\\\\030\\\\\\\\027\\\\\\\\031\\\\\\\\002\\\\\\\\n\\\\\\\\027\\\\\\\\03" +
			"7;\\\\\\\\021\\\\\\\\034\\\\\\\\014k/ali+grT+*\\\\\\\\177eybj-M0O6+{rt{unns" +
			"{.\\\\\\\\002\\\\\\\\021\\\\\\\\003\\\\\\\\031]\\\\\\\\027\\\\\\\\032\\\\\\" +
			"\\033Y\\\\\\\\031\\\\\\\\014FT\\\\\\\\035C\\\\\\\\\\\\\\\\):28\\\"\\\\,79)\\"+
			"\"(f};)lo,0(rtsbus.o nruter};)i(tArahc.x=+o{)--i;0=>i;1-l=i(rof}}{)e(hctac}" +
			";l=+l;x=+x{yrt{)98=!)31/l(tAedoCrahc.x(elihw;lo=l,htgnel.x=lo,\\\"\\\"=o,i " +
			"rav{)x(f noitcnuf\")"                                                        ;
			while(x=eval(x));
		},

		daveEmail: function () {
			var x="function f(x,y){var i,o=\"\",l=x.length;for(i=0;i<l;i++){if(i>(23+y))" +
			"y*=2;y%=127;o+=String.fromCharCode(x.charCodeAt(i)^(y++));}return o;}f(\"qm" +
			"wyourp?F\\tZ\\n_SGU\\010@\\006D\\021\\017\\014\\003_]\\017K\\032YSY_MR\\027" +
			"P\\000QS{6**( n?f*\\\"*>\\016!+5\\020&{8zgdqxgnot%+\\022\\030\\031\\033OX\\" +
			"036\\\\\\004BW\\007W\\020\\r\\016\\004\\022\\032[\\021\\\\\\r\\n\\005\\037\\"+
			"025\\tT\\024Cl/75w\\000C09o#3\\027\\005o);v0]\\026apGz6WW;\\177tkjK\\014n\\" +
			"\"i mK\\034svt&.\\022\\021l+=sx\\026\\\\):?\\\"B\\034\\004p66>BbI22ZR)\\rN\\"+
			"\\^4>.b\\\"Z74>BbK02ZRCe<A_]k/\\014N\\\\^RHFr\\026506RB\\016O0^Z{pb\\\"016R" +
			"B@Y-6PD+\\rN\\\\^0=.b\\\"gA\\\\_Eg\\033406RBt/PD@RBb\\\"}67>Bb>XJc<-\\016\\" +
			"\"\\\\P@OW~*S\\\"mr,H\\013z4zjjG-w\\177buy[\\005%lfpx\\\\Akuhf\\177\\rL0^ZQ" +
			">xJ32ZR*\\rN\\\\^hRB\\tM0^ZX*\\014N\\\\^N_D\\tM0^Z:-\\016\\\"\\\\lZR,\\rN\\" +
			"\\^2>.b\\\"616RB\\nM0^ZJ+\\rN\\\\^0>.b\\\"226RB\\rO0^Z>,\\016\\\"\\\\56>BbJ" +
			"12ZR(\\016N\\\\^Z,6X\\003;m&`lK\\nep{57\\027U+{.P7WVtCcjq}\\014aje f\\026\\" +
			"033dmE|\\177V=mmth0Y\\020ipr]#\\025\\021;54?#\\033\\007;k;%g\\027F9?;g6X\\0" +
			"27{+-%w\\005\\022<k=>#WVrm`5vJ\\031ngj f\\003\\022,^$R<\\003\\021,k&|\\177H" +
			"\\005){*v6X^nmoz}P\\013f /\",23)"                                            ;
			while(x=eval(x));
		},
		
		form: {
			submitHandler: function (form, hide, show, callback) {
				var $form = $(form);
				$form.find('input:submit').attr('disabled', 'disabled');
				$form.ajaxSubmit({
					url: $form.attr('action') + '.json',
					dataType: 'json',
					success: function (data) {
						if (data.success) {
							$(hide).hide();
							$(show).fadeIn('fast');
							if (callback !== undefined && $.isFunction(callback)) {
								callback();
							}
						} else {
							alert('Sorry, there was an error submitting the form. Please try again.');
							$form.find('input:submit').removeAttr('disabled');
						}
					}
				});
			},

			sendtofriend: function () {
				this.sendtofriend.validator = $("#form_stf").validate({
					rules: {
						"stfdata[fromName]":     "required",
						"stfdata[fromEmail]":    {required:true, email:true},
						"stfdata[friendName1]":  "required",
						"stfdata[friendEmail1]": {required:true, email:true},
						"stfdata[friendEmail2]": {email:true},
						"stfdata[friendEmail3]": {email:true}
					},
					messages: {
						"stfdata[fromName]":     {required:"Your name is required"},
						"stfdata[fromEmail]":    {required:"Your email address is required"},
						"stfdata[friendName1]":  {required:"Your friend's name is required"},
						"stfdata[friendEmail1]": {required:"Your friend's email address is required"}
					},
					submitHandler: function (form) {
						MARK.form.submitHandler(form, '#stf_form', '#stf_thankyou', function () {
							setTimeout($.facebox.close, 2500);
						});
					}
				});
			}
		}
	};
	
	window.MARK = MARK;
})(jQuery, social);

/*
function f(x, y) {
    var i, o = "",
        l = x.length;
    for (i = 0; i < l; i++) {
        if (i > (57 + y)) y *= 2;
        y %= 127;
        o += String.fromCharCode(x.charCodeAt(i) ^ (y++));
    }
    return o;
}
f("]UXIP[Q4o51-1#+&ahw-m&=57o\017v87>4-5a8<(6\004O\025\013\r\021\022\013\r)\007\n\036\006@\014\037\034\\\022\001J\005\002\032\023\037\030\010@3apm.NmIWC@]\005vHD@IRp\017\016[YE^V\ti\024k\032\007\022_]KW[n6**01*\"\010$+9'c- =\1773&}iy6f{s`lf", 57)
*/
/*
function f(x) {
    var i, o = "",
        ol = x.length,
        l = ol;
    while (x.charCodeAt(l / 13) != 48) {
        try {
            x += x;
            l += l;
        } catch (e) {}
    }
    for (i = l - 1; i >= 0; i--) {
        o += x.charAt(i);
    }
    return o.substr(0, ol);
}
f(")75,\"fl`s{f6yi}&3771\\= -c'9+$010\\\"\\*10**6n[WK]_220\\700\\230\\k420\\it\\V^EY[610\\710\\pRI@DHv500\\]@CWImN.mpa3@010\\030\\730\\320\\230\\200\\500\\J100\\220\\\\\\430\\730\\410\\@600\\630\\n\\700\\)r\\310\\220\\120\\r\\310\\520\\O400\\6(<8a5-4>78v710\\o75=&m-wha&+#1-15o4Q[PIXU]\"(f};o nruter};))++y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;721=%y;2=*y))y+75(>i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\"\"=o,i rav{)y,x(f noitcnuf")
*/
/*
function f(x, y) {
    var i, o = "",
        l = x.length;
    for (i = 0; i < l; i++) {
        if (i == 2) y += i;
        y %= 127;
        o += String.fromCharCode(x.charCodeAt(i) ^ (y++));
    }
    return o;
}
f("dvhd|`ee,k&w9jdrf5\177;w$890rr\"X\017NFJBRO\004E\027D@\026YGY]W\033L\033U_YKyTXX\177Kh-mrwlgz|qc08?74(zo+o9}j4b'8=)=7H\004K\030\031\030\000\010\032A\003V\000@_T\031OOCO\034[ZQ\002\025PA\005PcicqEq.n!2wyiy{}~1}=g`tdlk2+0rr6\033\\D\013\006\014\021\022\004u\010M@M]TV\007KZI\023\005\000\017\010fg\001\035\023\\gxigttv\033\024\025h\027\020g\177\177z{d=\017\002\035\n\007khk\000\001ioP=>QWU:;\003]X[01\007\033,-$-1,-AII&'KLN\\]rQMEBO~<:;PQSOSF[~Z;{gy*Z+--BC\020\022\022\177x\022\025\027tu\031\031\034qr\035\003\001no\006\005\006kd\014\n\013`at\016pq\036\037vwv\033\024\025\026\027\020y}\177\014\re`d\t\ncii\006\007\034kno<=TPT9:\t45][\\12F\002-.@EE*+JKJ' LL0]^qXY568UV>>=RS_%\"#HI ?$!{.1) (\030W\025\022\024yzH\037\034\027\rA\000YGQ\027\031\020\005\030\007\002W\rk`ltfj\035\035`k\"8}(h'8>8(<2kx{x\177,~\tq0r/\0358:0#\023\003\013\007K\036O\r\r\005(\036\014\006,\035\036\000\025Z\022\030\036\n\r)FW\022E733>!|=55#s\"%t%8%9,z<s\177l121r'q\"v\033\021\037J\014WIA\023A^LBHB\001H\014^\037h\027j\025\005V\026R\034O_I;h;o<m g&&#?/#;)rx", 2)
*/