var splashPlayer, pageTags, gp = '/storage/element/featured/2012-01-20/featured_0', gs = '.jpg',
    ctrlPosition = {x:1170,y:230},
    gt_logo = {'title':'geektyrant','href':'http://geektyrant.com/'},
    tag_elements = ['/news/category/','/news/tag/'],
	tagKW={ 'movie':'pop', 'tv':'pop', 'trailer':'pop', 'review':'pop', 'comic-book':'pop', 'exclusive':'pop', 'interview':'pop', 'podcast':'pop', 'photos':'pop', 'predictions':'pop', 'rant':'pop', 'rumor':'pop', 'blu-ray':'pop', 'toy':'pop', 'updated':'pop', 'book':'pop', 'contest':'pop', 'dvd':'pop', 'humor':'pop', 'game':'gaming', 'art':'art', 'concept-art':'art', 'music':'music', 'tech':'tech', 'videos':'video' },
    featItems = {
        f1: {
            'title': 'The Dark Knight Rises',
            'href': '/news/tag/the-dark-knight-rises'
        },
        f2: {
            'title': 'Sundance 2012',
            'href': '/news/tag/sundance-2012'
        },
        f3: {
            'title': 'Prometheus',
            'href': '/news/tag/prometheus'
        },
        f4: {
            'title': 'The Hunger Games',
            'href': '/news/tag/the-hunger-games'
        },
        f5: {
            'title': 'Chronicle',
            'href': '/news/tag/chronicle'
        }
    };
$(function(){
    gp = location.host.search(/geektyrantsquared.squarespace.com/ig)<0?'storage/element/featured/2012-01-20/featured_0':gp;
    for(var i=1;i<6;i++){$('<img/>').attr('src',gp+i+gs);}
    if($.cookie.read('play')==null) $.cookie.make('play',true,7);
    var splashTimer, splashTimerDelay, init = true, v=0, t=10, rad = 11, ft='featured_', ht='header', c=$('#vfxc'), h=$('#hdr'),
        p=function(v){return parseInt(v,10);}, attr = { fill: "#000", opacity: 0, "stroke-width": 0 };
	
    if(supportsSvg()||supportsVml()) {
        var R = Raphael("vfxi",1200,300),
            fClass = (c.attr('class')!='')?c.attr('class'):ft+'1',
            logo = R.path("M708.5,50.25H41V137H623.75L708.5,50.25Z").attr(attr).attr(gt_logo),
            hdr = {
                featured_1: R.path("M469.0,144.5L260.5,144.5L242.5,160.5L453.0,160.5Z").attr(attr).attr(featItems.f1),
                featured_2: R.path("M451.5,160.5L260,160.5L245,175.5L437,175.5Z").attr(attr).attr(featItems.f2),
                featured_3: R.path("M437,175.5L260,175.5L245,190.832L422,190.832Z").attr(attr).attr(featItems.f3),
                featured_4: R.path("M422,190L260,190L244,207L405,207Z").attr(attr).attr(featItems.f4),
                featured_5: R.path("M406,206L259,206L244,222L390,222Z").attr(attr).attr(featItems.f5)
            },
            overlay = R.path("M1200,250L362,250L613,0L1200,0Z").attr(attr).attr({'title':hdr[fClass].attrs.title,'href':hdr[fClass].attrs.href}).toBack(),
            ctrls = {
                timer: R.path().attr({stroke: "#fff", "stroke-width": 2}).attr({arc: [0, 10, rad]}),
                play: R.path("M0.499,0v8.834L5,4.333L0.499,0z").translate(ctrlPosition.x-2,ctrlPosition.y-4).attr({stroke: "none", fill: "#fff"}),
                pause: R.path("M3.334,0.126v8.583h1.873V0.126H3.334z M0,8.792h1.874V0.209H0V8.792z").translate(ctrlPosition.x-3,ctrlPosition.y-4).attr({stroke: "none", fill: "#fff"}),
                btn: R.circle(ctrlPosition.x,ctrlPosition.y,11).attr({stroke: "none", fill: "#fff",opacity:0}).click(function(e){
                        if(!$.cookie.read('play')) {
                            ctrls.play.hide(); ctrls.pause.show();
                            $(ctrls.play[0]).hide(); $(ctrls.pause[0]).show();
                            $.cookie.make('play',true);
                            splashPlayer();
                        } else {
                            clearTimeout(splashTimer);
                            ctrls.play.show(); ctrls.pause.hide();
                            $(ctrls.pause[0]).hide(); $(ctrls.play[0]).show();
                            $.cookie.make('play',false,7);
                        }
                    }).toFront()
            };
		  logo.toFront();

        R.customAttributes.arc = function (value, total, rad) {
            var alpha = 360 / total * value, a = (90 - alpha) * Math.PI / 180, x = ctrlPosition.x + rad * Math.cos(a), y = ctrlPosition.y - rad * Math.sin(a);
            return {
                stroke:"rgba(255,255,255,"+(value/total)+")",
                path:(total == value)?[["M",ctrlPosition.x,ctrlPosition.y-rad],["A",rad,rad,0,1,1,ctrlPosition.x-.01,ctrlPosition.y-rad]]:[["M",ctrlPosition.x,ctrlPosition.y-rad],["A",rad,rad,0,+(alpha>180),1,x,y]]
            };
        };

        if(init && !$.cookie.read('play')) {
            ctrls.play.show(); ctrls.pause.hide();
            $(ctrls.play[0]).show(); $(ctrls.pause[0]).hide();
        } else {
            ctrls.play.hide(); ctrls.pause.show();
            $(ctrls.play[0]).hide(); $(ctrls.pause[0]).show();
        }
        ctrls.btn[0].style.cursor = "pointer";

        for (var f in hdr) {
            $(hdr[f][0]).css({cursor:"pointer"}).attr('id',f).mouseover(function(){
                clearTimeout(splashTimerDelay); clearTimeout(splashTimer);
                var iid = $(this).attr('id');
                c.hide().stop(true,true).removeClass().addClass(iid).fadeIn('normal',function(){
                    h.removeClass().addClass(ht+' '+iid);
                });
                overlay.attr(featItems['f'+p(iid.split(ft)[1])]);
                R.safari();
            }).mouseout(function(){
                clearTimeout(splashTimerDelay); clearTimeout(splashTimer);
                if($.cookie.read('play')) splashTimerDelay = setTimeout("splashPlayer()", 500);
            });
        }

        function updateVal(value, total, rad, timer, id) {
            var ftItem = p(c.attr('class').split(ft)[1]), color = "rgba(255,255,255,"+(value/total)+")";
                ftItem = (init||isNaN(ftItem)||ftItem>4)?1:ftItem+1;
            if (!value || value == total) {
                if(!$.cookie.read('play')) {
                    c.hide().removeClass().addClass(ft+ftItem).fadeIn('normal',function(){
                        h.removeClass().addClass(ht+' '+ft+ftItem);
                    });
                    init=false;
                } else {
                    timer.animate({arc: [total, total, rad],opacity:0.3}, 300, "linear", function () {
                        timer.attr({arc: [0, total, rad],opacity:1});
                        overlay.attr(featItems['f'+ftItem]);
                        c.hide().removeClass().addClass(ft+ftItem).fadeIn('normal',function(){
                            h.removeClass().addClass(ht+' '+ft+ftItem);
                        });
                        init=false;
                    });
                }
            } else {
                timer.animate({arc: [value, total, rad],opacity:1}, 300, "linear");
            }
        }
    }
    
    function supportsVml() {
        if (typeof supportsVml.supported == "undefined") {
            var a = $('<div>').html('<v:shape id="vml_flag1" adj="1" />').children().css('behavior','url(#default#VML)')[0];
            supportsVml.supported = a ? typeof a.adj == "object": true;
        }
        return supportsVml.supported;
    }
    function supportsSvg() { return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") }

    splashPlayer = function(){
        if(!supportsSvg()&&!supportsVml()) {
            clearTimeout(splashTimer);
            var ftItem = p(c.attr('class').split(ft)[1]);
            ftItem = (init||isNaN(ftItem)||ftItem>4)?1:ftItem+1;
            if(init) {
                $('#vfxi').click(function(){
                    location.href=this.href;
                    return true;
                });
                $('#vfxi').flkr(function(d){
                    clearTimeout(splashTimer);
                    var fi = (p(c.attr('class').split(ft)[1])+d.dir);
                    fi = (fi<1)?5:(fi>5)?1:fi;
                    $('#vfxi').attr('href',featItems['f'+fi].href);
                    c.hide().stop(true,true).removeClass().addClass(ft+fi).fadeIn('normal',function(){
                        h.removeClass().addClass(ht+' '+ft+fi);
                        splashTimer = setTimeout("splashPlayer()", 3500);
                    });
                    return false;
                });
                init=false;
            }
            $('#vfxi').attr('href',featItems['f'+ftItem].href);
            c.hide().removeClass().addClass(ft+ftItem).fadeIn('normal',function(){
                h.removeClass().addClass(ht+' '+ft+ftItem);
            });
            splashTimer = setTimeout(arguments.callee, 3500);
        } else {
            if(v>=t) v=0; updateVal(v, t, 11, ctrls.timer, 4); v++;
            if($.cookie.read('play')) splashTimer = setTimeout(arguments.callee, 300);
        }
    };
    splashPlayer();

    
    $('.posted-on').timeago();
	$('.tag-element').each(function(){
	   var l = $(this).children('a').attr('href');
	   for(var h=0;h<tag_elements.length;h++){if(l.indexOf(tag_elements[h])>=0){$(this).children('a').addClass(l.split(tag_elements[h])[1]);pageTags=ov(l.split(tag_elements[h])[1],tagKW); break;}}
	});
	    
	$('.list-journal-entry-wrapper').on('click','.journal-entry-wrapper .journal-entry-text a.btn_social',function(){
		var $t=$(this);
		window.open($t.attr('href'),$t.attr('title'),'width=850,height=830,left=120,top=100');
		return false;
	});
});

function ov(k,o){return o.hasOwnProperty(k)?o[k]:o[0];}
(function($) {
    $.cookie = {
        make: function(name,value,days) {
        	if (days) {
        		var date = new Date();
        		date.setTime(date.getTime()+(days*24*60*60*1000));
        		var expires = "; expires="+date.toGMTString();
        	} else { var expires = ""; }
        	document.cookie = name+"="+value+expires+"; path=/";
            return value;
        },
        read: function(name) {
        	var nameEQ = name + "=";
        	var ca = document.cookie.split(';');
        	for(var i=0;i < ca.length;i++) {
        		var c = ca[i], op;
        		while (c.charAt(0)==' ') c = c.substring(1,c.length);
        		if (c.indexOf(nameEQ) == 0) {
                    op = c.substring(nameEQ.length,c.length);
                    op = (op!='true'&&op!='false')?op:(op=='true')?true:false;
                    return op;
                }
        	}
        	return null;
        },
        del: function(name) {
        	$.cookie.make(name,"",-1);
        }
    };
    $.fn.flkr = function(options) {
        var fC = { dir: 0, isFlick: false },
            def = { threshold: 20, d:-1, u:1 };
        fC.s = function(e) {
            var $el = $(e.target);
            this.isFlick = false;
            this.startX = event.targetTouches[0].clientX;
            this.startY = event.targetTouches[0].clientY;
            $el.bind('touchmove', fC.m);
            $el.bind('touchend', fC.e);
            return false;
        };
        fC.m = function(e) {
            event.preventDefault(); //no scrolling
            this.movedY = event.targetTouches[0].clientY;
            if (Math.abs(Math.abs(this.movedY) - Math.abs(this.startY)) > def.threshold) {
                this.isFlick = true;
                fC.dir = (this.movedY > this.startY)?def.d:def.u;
            }
        };
        fC.e = function(e) {
            var $el = $(e.target);
            if (this.isFlick) { options({ dir: fC.dir }); this.isFlick=false; } else { $el.trigger('click'); }
            $el.unbind('touchmove touchend');
        };
        $(this).bind('touchstart', fC.s);
        return fC;
    };
})(jQuery);
