﻿var linkClass = 'link';

var BoxLink = new Class({
	initialize: function(el){
		var link = el.getElement("a");
		if(link){
			el.addClass(linkClass);
			var parent = link.getParent();
			if(el.id.contains("artist")){
			    var id = el.id.split('_')[1];
			    var add = new Element('a', {
			        'href': '/program/program/',
			        'events': {
			            'click': function(e){
			                e.stop();
			                addToCalendar(id);
			            }
			        },
			        "html": "L&auml;gg till i mitt program"
			    });
			    parent.appendText(" - ");
			    add.inject(parent);
			}
			el.addEvent('click', function(){
				window.location = link;
			});
		}
	}
});

var CommentBrowser = new Class({						   
	speed: 5,
	fadetime: 1500,
	initialize: function(holder, source){
		this.holder = holder;
		this.holder.empty();
		this.chain = new Chain();
		var request = new Request.JSON({ "url": source, "onComplete": this.loaded.bind(this) }).send();
	},
	loaded: function(obj) {
		var comments = obj.comments;
		comments.each(function(comment, index){			
			var el = new Element("div", { 
				"class": "item clearfix " + linkClass,
				"id": "comment" + (index + 1),
				"events": {
					"click": function(){
						window.location = comment.url;
					}
				}
			}).adopt(
				new Element("p").adopt(
					new Element("strong", { "text": comment.author + " skrev:" }),
					new Element("span", { "text": comment.text })
				)
			);
			this.add(el);			
		 }.bind(this));
		 
		var runChain = function() { 
			this.chain.callChain();
			if (this.chain["$chain"].length == 0) { runChain = $clear(timer); } 
		}.bind(this);
		
		var timer = runChain.periodical(this.speed * 1000);
	},
	add: function(el){
		this.chain.chain(
			function() { 
				this.next(el); 
			}.bind(this)
		);
		this.holder.adopt(el);
	},
	next: function(el){		
		el.oldStyle = el.getStyles('height', 'visibility', 'opacity', 'margin');
		el.set("tween", { "duration": this.fadetime, onComplete: function(){
				this.add(el);
				el.setStyles(el.oldStyle);		
			}.bind(this)
		});
		el.tween("margin-top", -62);
	}
});

var Comments = {
    init: function(){
        var browser = $('senaste_kommentarerna_browser');
	    if(browser){
		    new CommentBrowser(browser, "/functions/comments.ashx");
	    }
    }
}

var calendar = {
    init: function(){
        var calendar = $('Program_calendar_main');
    	
	    if(calendar){
	        var items = $$('div#Program_calendar_main div.item');
	        items.each(function(el){
	            el.addEvent('mouseenter', function(){
	                el.addClass('over');
	            });
    	        
	            el.addEvent('mouseleave', function(){
	                el.removeClass('over');
	            });
	        });
	    }
	}
}

var boxLinks = {
	init: function(){
		$$('div#artist_list div.item, div#generic_list div.item, div#bloggen div.item, div#calendar div.item, div#tavling').each( function(el){
			var myBoxLink = new BoxLink(el);
		});
	}
}

window.addEvent('load', function() {
    boxLinks.init();
	calendar.init();
    Comments.init();
    /*moopop.captureByRel('popup');*/
    getCalendarInfo();
});

function addToCalendar(id, el) {
    var ajax = new Request({
        url: '/functions/addToCalendar.ashx?id=' + id, 
        method: 'get', 
        onComplete: function(response){
            getCalendarInfo();
            if (el != undefined){
                el.getParent().getParent().getParent().addClass("sel");
                el.getParent().set("html", '<a href=\"/program/program/\" onclick=\"removeFromCalendar(this, ' + id + '); return false;\" title=\"Ta bort evenemang\">-</a>');
            }
        }
    }).send();
}

function removeFromCalendar(el, id) {
    var ajax = new Request({
        url: '/functions/removeFromCalendar.ashx?id=' + id, 
        method: 'get', 
        onComplete: function(response){
            getCalendarInfo();
            el.getParent().getParent().getParent().removeClass("sel");
            el.getParent().set("html", '<a href=\"/program/program/\" onclick=\"addToCalendar(' + id + ', this); return false;\" title=\"L&auml;gg till evenemang\">+</a>');
        }
    }).send();
}

function getCalendarInfo() {
    if ($('kalender_info')) {
        $('kalender_info').load('/functions/getCalendarInfo.ashx?ms=' + new Date().getTime());
	}
}

/*
  moopop by gonchuki - http://blog.gonchuki.com
*/

var moopop = {
  width: 0,
  height: 0,
  captureByRel: function(attrVal, parent) {
    this.capture($ES('a', parent || document).filterByAttribute('rel', '*=', attrVal));
  },
  capture: function(el, width, height) {
    if ($defined(width) && $defined(height)) {
      this.width = width;
      this.height = height;
    }
    switch ($type(el)) {
      case 'element':
        this.add_pop_to(el);
        break;
      case 'string':
      case 'array':
        $$(el).each( function(el) {
          this.add_pop_to(el);
        }, this);
        break;
    }
    this.width = null;
    this.height = null;
  },
  add_pop_to: function(el) {
    el.addEvent('click', function(e){ new Event(e).stop(); this.popup(el); }.bind(this));
    
    var size = el.getAttribute('rel').match(/\[(\d+),\s*(\d+)\]/) || ['', this.width, this.height];
    
    if (size[1]) el.setAttribute('popupprops', 'width=' + size[1] + ', height=' + size[2] );
  },
  popup: function(el) {
    window.open(el.href, '', el.getAttribute('popupprops') || '');
  }
};

var LastFM = new Class({
	initialize: function(){
	},
	get: function(name, method, onComplete){
		new Request.JSONP({
			url: "http://ws.audioscrobbler.com/2.0/",
			data: {
				"format": "json",
				"lang": "sv",
				"api_key": "265f41dedf21450c9c8da8e6cd810ff8",
				"artist": name + "",
				"method": "artist." + method,
				"callback": onComplete
			}
		}).send();
	}
});
var Flickr = new Class({
	initalize: function(name){
	},
	get: function(name, onComplete){
		new Request.JSONP({
			url: "http://api.flickr.com/services/rest/?",
			data: {
				"format": "json",
				"api_key": "9a907871b9379453547b642189c50bf0",
				"text": "\"" + name + "\"",
				"tags": "musik, music, concert, konsert",
				"method": "flickr.photos.search",
				"jsoncallback": "Artist.images",
				"sort": "relevance",
				"media": "photos"
			}
		}).send();
	}
});
var Artist = {
	init: function(){
		var el = $("artist_content");
		var header = $("artist_head");
		if(el != null && header != null){
			Artist.el = el;
			Artist.header = header.getElement("h3");
			var name = Artist.header.get("text");
			if($$("input[name=show_spotify]") && $$("input[name=show_spotify]")[0] && $$("input[name=show_spotify]")[0].get("value") == "1"){
				Artist.music = new Element("div", { "class": "fadebox_line popular-music" }).adopt(
					new Element("h3", { "text": "Populära låtar & album" }),
					new Element("div", { "class": "popular-music-wrapper clearfix" }),
					new Element("p", { "html": "<em>Baseras på statistik från <a href=\"http://www.last.fm\">last.fm</a></em>" })
				).inject(Artist.el, "after");
				var lastfm = new LastFM();
				lastfm.get(name, "gettoptracks", "Artist.tracks");
				lastfm.get(name, "gettopalbums", "Artist.albums");
			}
			if($$("input[name=show_flickr]") && $$("input[name=show_flickr]")[0] && $$("input[name=show_flickr]")[0].get("value") == "1"){
				Artist.flickr = new Element("div", { "class": "fadebox_line flickr-feed" }).adopt(
					new Element("h3", { "text": "Bilder" }),
					new Element("p", { "html": "<em>Bilder från <a href=\"http://www.flickr.com/search/?q='" + escape(name) + "'\">flickr.com</a></em>" })
				).inject(Artist.el, "after");
				
				var flickr = new Flickr();
				flickr.get(name, Artist.images);
			}
			sIFR.replace(bell_gothic_light, {
				selector: 'div#main h3, div#artist_head h4'
				,css: ['.sIFR-root {color: #000000; text-transform: uppercase; letter-spacing: -1.5}']
				,wmode: 'transparent'
				,fitExactly: true
				,tuneHeight: -9
			});
		}
	},
	images: function(obj){
		var items = obj.photos.photo;
		if(items && items.length > 0){
			var list = new Element("ul", { "class": "thumb_list clearfix" }).inject(Artist.flickr.getElement("p"), "before");
			(items.length > 4 ? 4 : items.length).times(function(i){
				var item = items[i];
				var url = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret;
				new Element("li").adopt( new Element("a", { "href": url + ".jpg", "rel": "lightbox" }).adopt( new Element("img", { "src": url + "_t.jpg" }) ).slimbox() ).inject(list);
			});
		}else{
			Artist.flickr.destroy();
		}
	},
	tracks: function(obj, name){
		if(obj.toptracks.track){
			new Artist.List("Låtar", obj.toptracks.track, "title", obj.toptracks["@attr"].artist);
		}
	},
	albums: function(obj){
		if(obj.topalbums.album){
			new Artist.List("Album", obj.topalbums.album, "album", obj.topalbums["@attr"].artist);
		}
	},
	List: new Class({
		initialize: function(title, items, type, name){
			if(items.length > 0){
				var el = new Element("div", { "class": "popular-music-list" }).inject(Artist.music.getElement("div.popular-music-wrapper"));
				var header = new Element("h4", { "text": title }).adopt(new Element("span", { "text": "Lyssna i Spotify" })).inject(el);
				var list = new Element("ul").inject(el);
				(items.length > 5 ? 5 : items.length).times(function(i){
					var track = items[i].name;
					new Element("li").adopt(
						new Element("span", { "text": (i+1) + ". " }).adopt(
							new Element("a", {
								"href": "spotify:search:" + type + "%3a%22" + track + "%22+artist%3a%22" + name + "%22",
								"text": track,
								"title": "Öppna i Spotify"
							})
						),
						new Element("a", {
							"href": "spotify:search:" + type + "%3a%22" + track + "%22+artist%3a%22" + name + "%22",
							"text": "Öppna i Spotify",
							"title": "Öppna i Spotify",
							"class": "spotify" 
						})
					).inject(list);
				});
			}
		}
	})
}
window.addEvent("load", Artist.init);

var Connect = {
	key: "50bc3abd9ab517665c6c6c4785f970a1",
	xd: "/connect/xd_receiver.htm",
	login: function(){
		Connect.wrapper = $("facebook-login");
		if(Connect.wrapper && !Connect.loggedIn ){
			Connect.loggedIn = true;
			var api = FB.Facebook.apiClient;
			var user = api.get_session().uid;
			api.users_getInfo(user, "name", function(obj){
				Connect.wrapper.getElements("p").each(function(el){
					el.setStyles({ "opacity": 0, "height": 0, "width": 0, "margin": 0, "overflow": "hidden" });
				});
				var info = obj[0];
				Connect.name = info.name;
				Connect.button = new Element("input", { "type": "submit", "class": "btn_orange", "value": "Skicka!" });
				Connect.button.inject(Connect.wrapper);
				Connect.button.addEvent("click", Connect.submit);
				
				var info = new Element("div", { "class": "facebook-info clearfix" }).adopt(
					new Element("fb:profile-pic", { "uid": user }),
					new Element("h4").adopt(new Element("fb:name", { "uid": user, "linked": false, "useyou": false })),
					new Element("p").adopt(
						new Element("a", { "href": "#logout", "text": "Logga ut", "events": { "click": Connect.logout } })
					)
				);
				info.replaces(Connect.wrapper.getParent().getElement("h4"));
				FB.XFBML.Host.parseDomTree();
			});
		}
	},
	submit: function(e){
		e.stop();
		Connect.wrapper.addClass("fb-loading");
		Connect.field = $$("textarea[name=comment]")[0];
		Connect.button.set("disabled", true);
		var page = $$("input[name=page_id]")[0];
		var url = $$("input[name=page_url]")[0];
		var title = $$("input[name=page_title]")[0];
		var data = {
			api: Connect.key,
			name: Connect.name,
			comment: Connect.field.get("value"),
			page: page.get("value"),
			action: 'har skrivit en kommentar på <a href="' + url.get("value") + '">Sundsvalls Gatufest</a>',
			action2: 'kommenterade sidan <a href="' + url.get("value") + '">' + title.get("value") + '</a>:'
		};
		var checkbox = $$("input[name=publish_comment]")[0];
		if(checkbox.get("checked")){
			var feed = FB.Connect.showFeedDialog(82300601369, data);
			//alert(feed);
		}
		var json = new Request.JSON({ url: "/functions/addComment.ashx", "method": "post", data: data, onComplete: Connect.complete }).send();
	},
	complete: function(json){
		Connect.wrapper.removeClass("fb-loading");
		Connect.field.set("value", "");
		Connect.button.setStyle("display", "none");
		var comment = json.response;
		var pic = new Element("fb:profile-pic", { "uid": comment.user });
		var el = new Element("div", { "class": "item clearfix", "morph": { "duration": 500 } }).adopt(
			new Element("div", { "class": "picture" }).adopt(pic),
			new Element("div", { "class": "text" }).adopt(
				new Element("p", { "class": "date", "html": "<em>" + comment.added + "</em>" }),
				new Element("h4", { "text": comment.name + " skrev:" }),
				new Element("p", { "html": comment.comment })
			)
		).inject(Connect.wrapper.getParent(), "after");
		FB.XFBML.Host.parseDomTree();
		
		var styles = el.getStyles("padding-top", "padding-bottom");
		styles.height = el.getSize().y - styles["padding-top"] - styles["padding-bottom"];
		styles.opacity = 1;
		el.setStyles({ "height": 0, "padding-top": 0, "padding-bottom": 0, "opacity": 0, "overflow": "hidden" });
		el.morph(styles);
	},
	logout: function(e){
		e.stop();
		var url = $$("input[name=page_url]")[0];
		FB.Connect.logoutAndRedirect(url.get("value"));
	}
}