﻿
// cookie functions
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = jQuery.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// /cookie functions

// fixes for IE-7 cleartype bug on fade in/out
jQuery.fn.fadeIn = function(speed, callback) {
    return this.animate({ opacity: 'show' }, speed, function() {
        if (jQuery.browser.msie) this.style.removeAttribute('filter');
        if (jQuery.isFunction(callback)) callback();
    });
};

jQuery.fn.fadeOut = function(speed, callback) {
    return this.animate({ opacity: 'hide' }, speed, function() {
        if (jQuery.browser.msie) this.style.removeAttribute('filter');
        if (jQuery.isFunction(callback)) callback();
    });
};

jQuery.fn.fadeTo = function(speed, to, callback) {
    return this.animate({ opacity: to }, speed, function() {
        if (to == 1 && jQuery.browser.msie) this.style.removeAttribute('filter');
        if (jQuery.isFunction(callback)) callback();
    });
};


// liquid <> fixed
function setPageWidth() {
    var currentWidth = jQuery('#page').css('width');
    if (currentWidth == "95%") newWidth = "960px"; else if (currentWidth == "960px") newWidth = "95%"; else newWidth = "960px";
    jQuery("#page").animate({ width: newWidth }, 333).fadeIn("slow");
    jQuery.cookie('pageWidth', newWidth);
}

// body font size
function setFontSize() {
    var size = jQuery.cookie('fontSize');
    if (size == '.8em') newSize = '.95em';
    else if (size == '.95em') newSize = '.7em';
    else if (size == '.7em') newSize = '.8em';
    else newSize = '.95em';
    jQuery("body").animate({ fontSize: newSize }, 333).fadeIn("slow");
    jQuery.cookie('fontSize', newSize)
}

// minitabs
jQuery.fn.minitabs = function(speed, effect) {
    id = "#" + this.attr('id')
    jQuery(id + ">DIV:gt(0)").hide();
    jQuery(id + ">UL>LI>A:first").addClass("current");
    jQuery(id + ">UL>LI>A").click(
    function() {
        jQuery(id + ">UL>LI>A").removeClass("current");
        jQuery(this).addClass("current");
        jQuery(this).blur();
        var re = /([_\-\w]+$)/i;
        var target = jQuery('#' + re.exec(this.href)[1]);
        var old = jQuery(id + ">DIV");
        switch (effect) {
            case 'fade':
                old.fadeOut(speed).fadeOut(speed);
                target.fadeIn(speed);
                break;
            case 'slide':
                old.slideUp(speed);
                target.fadeOut(speed).fadeIn(speed);
                break;
            default:
                old.hide(speed);
                target.show(speed)
        }
        return false;
    }
 );
}

function initTooltips(o) {
    var showTip = function() {
        var el = jQuery('.tip', this).css('display', 'block')[0];
        var ttHeight = jQuery(el).height();
        var ttOffset = el.offsetHeight;
        var ttTop = ttOffset + ttHeight;
        jQuery('.tip', this)
	  .stop()
	  .css({ 'opacity': 0, 'top': 2 - ttOffset })
  	  .animate({ 'opacity': 1, 'top': 18 - ttOffset }, 250);
    };
    var hideTip = function() {
        var self = this;
        var el = jQuery('.tip', this).css('display', 'block')[0];
        var ttHeight = jQuery(el).height();
        var ttOffset = el.offsetHeight;
        var ttTop = ttOffset + ttHeight;
        jQuery('.tip', this)
	  	.stop()
	  	.animate({ 'opacity': 0, 'top': 10 - ttOffset }, 250, function() {
	  	    el.hiding = false;
	  	    jQuery(this).css('display', 'none');
	  	}
      );
    };
    jQuery('.tip').hover(
	  function() { return false; },
	  function() { return true; }
	);
    jQuery('.tiptrigger, #sidebar .cat-item').hover(
	  function() {
	      var self = this;
	      showTip.apply(this);
	      if (o.timeout) this.tttimeout = setTimeout(function() { hideTip.apply(self) }, o.timeout);
	  },
	  function() {
	      clearTimeout(this.tttimeout);
	      hideTip.apply(this);
	  }
	);
}

function getQuerystring(key, sUrl, default_) {
 if (default_==null) default_="";
 key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
 var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
 var qs = regex.exec(sUrl);
 if(qs == null)
   return default_;
 else
   return qs[1];
}

function initYoutubeVideo() {
	if($("#youtubecontainer").length > 0) {
		$(".youtubecontent a").bind(
		    "click",
		    function(event) {
			var videoid = getQuerystring("v", this.href);
	    
			if(videoid) {
				event.preventDefault();
				
				attachYoutubeVideo(videoid);
				
				
			} else {
				 this.target = "_blank";
			}
		    }
		);
	}
}

function attachYoutubeVideo(videoid) {
	
	// Lets Flash from another domain call JavaScript
	var params = { allowScriptAccess: "always" };

	// The element id of the Flash embed
	var atts = { id: "ytPlayer" };
	// All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
	swfobject.embedSWF("http://www.youtube.com/v/" + videoid + "&enablejsapi=1&playerapiid=player1&autoplay=1",
		   "youtubecontainer", "630", "379", "8", null, null, params, atts);
	
}

function tabmenudropdowns() {
    jQuery(" #tabs ul ul ").css({ display: "none" }); // Opera Fix
    jQuery(" #tabs li").hover(function() {
        jQuery(this).find('ul:first').css({ visibility: "visible", display: "none" }).show(333);
    }, function() {
        jQuery(this).find('ul:first').css({ visibility: "hidden" });
    });
}

// comment.js by mg12 - http://www.neoease.com/
(function() {
    function $$$(id) { return document.getElementById(id); }
    function setStyleDisplay(id, status) { $$$(id).style.display = status; }

    window['MGJS'] = {};
    window['MGJS']['$$$'] = $$$;
    window['MGJS']['setStyleDisplay'] = setStyleDisplay;

})();


(function() {
    function quote(authorId, commentId, commentBodyId, commentBox) {
        var author = MGJS.$$$(authorId).innerHTML;
        var comment = MGJS.$$$(commentBodyId).innerHTML;

        var insertStr = '<blockquote cite="#' + commentBodyId + '">';
        insertStr += '\n<strong><a href="#' + commentId + '">' + author.replace(/\t|\n|\r\n/g, "") + '</a> :</strong>';
        insertStr += comment.replace(/\t/g, "");
        insertStr += '</blockquote>\n';

        insertQuote(insertStr, commentBox);
    }

    function insertQuote(insertStr, commentBox) {
        if (MGJS.$$$(commentBox) && MGJS.$$$(commentBox).type == 'textarea') {
            field = MGJS.$$$(commentBox);

        } else {
            alert("The comment box does not exist!");
            return false;
        }

        if (document.selection) {
            field.focus();
            sel = document.selection.createRange();
            sel.text = insertStr;
            field.focus();

        } else if (field.selectionStart || field.selectionStart == '0') {
            var startPos = field.selectionStart;
            var endPos = field.selectionEnd;
            var cursorPos = startPos;
            field.value = field.value.substring(0, startPos)
					  + insertStr
					  + field.value.substring(endPos, field.value.length);
            cursorPos += insertStr.length;
            field.focus();
            field.selectionStart = cursorPos;
            field.selectionEnd = cursorPos;

        } else {
            field.value += insertStr;
            field.focus();
        }
    }

    window['MGJS_CMT'] = {};
    window['MGJS_CMT']['quote'] = quote;

})();

function getShops(strTitle) {
    var searchString = strTitle.replace("&#8211;", "");
	var H=[];
	H.push('<ul class="shops">');
	H.push('<li><a href="http://clk.tradedoubler.com/click?p=23762&a=1665961&g=11617567&url=http://phobos.apple.com/WebObjects/MZSearch.woa/wa/com.apple.jingle.search.DirectAction/search?term=' + encodeURIComponent(searchString) + '" target="_blank" class="buy itunes" onclick="pageTracker._trackPageview(\'/buy/itunes/'+escape(strTitle)+'\');">Köp via Itunes</a></li>');
	H.push('<li><a href="#" target="_blank" class="buy cdon" onclick="buyItem(\'' + encodeURIComponent(searchString) + '\');return false">Köp via CDon</a></li>');
	H.push('</ul>');
	$('p.more').prepend(H.join(""));
}

function buyItem(strTitle) {
    pageTracker._trackPageview('/buy/cdon/' + encodeURIComponent(strTitle) + '/');
    messureImg('http://impse.tradedoubler.com/imp?type(inv)g(16153296)a(1665961)' + new String (Math.random()).substring (2, 11));
    window.open('http://clk.tradedoubler.com/click?p=46&a=1665961&url=http://cdon.se/search?q=' + strTitle);

}

function buyConsert(strTitle){

	pageTracker._trackPageview('/buy/ticnet/' + encodeURIComponent(strTitle) + '/');
	messureImg('http://impse.tradedoubler.com/imp?type(inv)g(17810842)a(1665961)' + new String (Math.random()).substring (2, 11));
	window.open('http://clk.tradedoubler.com/click?p=81376&a=1665961&g=17810842&url=http://www.ticnet.se/search.php?tm_link=tm_homeA_header_search&language=sv&keyword=' + strTitle);
}

function shareIcons() {
	
	if(jQuery(".single-page").length > 0) {
	
		concertLinks();
		
		social.socialInit();
	
		//Old facebook implementation
		//jQuery(".tags").before('<div id="fb-root"></div>');
		
	
		//	var htmlString =  '<fb:like href="' + encodeURIComponent(location.href) + '" layout="standard" show_faces="false" width="450" action="like" colorscheme="light" />';
		//	jQuery("#fb-root").append('<div id="facebook-like">' +htmlString + '</div>');	
			
		//	setTimeout(function(){ 

		//	  window.fbAsyncInit = function() {
		//		FB.init({appId: '3207886a03b6ed3e42683d6f128d13fc', status: true, cookie: true,
		//				 xfbml: true});
		//	  };
		//	  (function() {
		//		var e = document.createElement('script'); e.async = true;
		//		e.src = document.location.protocol +
		//		  '//connect.facebook.net/sv_SE/all.js';
		//		document.getElementById('fb-root').appendChild(e);
					
		//	  }());
			  
		//	}, 10);
		
	}
}

function messureImg(sUrl) {
    var oImg = document.createElement("img");
    oImg.setAttribute('src', sUrl);
    oImg.setAttribute('height', '1px');
    oImg.setAttribute('width', '1px');
    document.body.appendChild(oImg);
}

function concertLinks() {
	
	var strTitle = jQuery("p.tags a").text();
	jQuery(".event-name").click(function(event) {
		buyConsert(strTitle);
	});

}

function getAlbumCovers() {

var iSize = Math.round($(window).width() / 120);

	$('#footer').html('<div class="album-cover-container"><button class="prev"></button><div id="result">Loading albumcovers...</div><button class="next"></button></div>');


	$(".album-cover-container").width($(window).width());
	  $.getJSON('/albumcovers/covers.js', function(data) {
	  
		var H=[];
		H.push('<div class="carousel">');
		H.push('<ul class="music">');
			$.each(data.items, function() {
				H.push('<li class="vinyl"><a href="' + this.link+'">');
				H.push('<span class="cover" title="' + this.title + '"></span>');
				H.push('<img src="'+this.img+'" alt="' + this.title + '" width="128" height="128">');
				H.push('</a></li>');
			});
		H.push('</ul></div>');
	  $('#result').html(H.join(""));
	  
	  
	  $(function() {
	    $(".carousel").jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev",
		visible: iSize,
		scroll:iSize
	    });
	});

	});
}
var social = { 
	aItems: 4, 
	aItemsArr: null, 
	setIconSize: 2, 

	socialInit: function() { 
		social.setSocialItems();
	}, 
	setSocial: function() { 
		var strCssClass; 
		switch (social.setIconSize) { 
		case 1: 
			strCssClass = '16'; 
			break; 
			
		case 2:
			strCssClass = '32'; 
			break; 

		case 3:
			strCssClass = '64'; 
			break; 
			default:
		}
	

		
		var H=[];
		H.push('<div class="social-bookmarks"><ul>');		
		for (i = 0; i < social.aItems; i++) { 
			H.push('<li><a href="' + aItemsArr[i][2] + '" title="Posta till ' + aItemsArr[i][0] + '" target="_blank" onClick="javascript: pageTracker._trackPageview(&#39;/outgoing/' + aItemsArr[i][0] + '&#39;);" class="icon social ' + aItemsArr[i][1] + strCssClass + '"><span>Posta till ' + aItemsArr[i][0] + '</span></a></li>');
		}
		H.push('</ul></div>');
		$("p.postmetadata").before(H.join(""));
		

	}, 
	
	setSocialItems: function() { 
		var dUrl = encodeURIComponent(document.location); 
		var dTitle = encodeURIComponent(document.title); 
		aItemsArr = new Array(social.aItems); 
		
		for (i = 0; i < aItemsArr.length; i++) { 
			aItemsArr[i] = new Array(3);
		}
		aItemsArr[0][0] = "Del.icio.us"; 
		aItemsArr[0][1] = "delicious"; 
		aItemsArr[0][2] = "http://del.icio.us/post?url=" + dUrl + "&title=" + dTitle; 
		
		aItemsArr[1][0] = "Facebook"; 
		aItemsArr[1][1] = "facebook"; 
		aItemsArr[1][2] = "http://www.facebook.com/share.php?u=" + dUrl + "&title=" + dTitle; 
		
		aItemsArr[2][0] = "Twitter"; 
		aItemsArr[2][1] = "twitter"; 
		aItemsArr[2][2] = "http://twitter.com/home?status=" + dUrl + "&title=" + dTitle; 
		
		aItemsArr[3][0] = "Technorati"; aItemsArr[3][1] = "technorati"; 
		aItemsArr[3][2] = "http://technorati.com/faves?add=" + dUrl + "&title=" + dTitle; 
		
		social.setSocial();
	}
}; 

jQuery(document).ready(function(){

	//insert albumcovers
	getAlbumCovers();

	//insert share Icons;
	shareIcons();


	jQuery('a.spotify').each(function (i) {


	var spotifyLinkLength;
	var spotifyLinkPrefix;
	var spotifyType;
	
		if(this.href.indexOf("/track/", 0) > 0) {
			
			spotifyLinkLength = parseInt(this.href.indexOf("/track/", 0) + 7,10);
			spotifyLinkPrefix= 'spotify:track:';
			spotifyType = 'track';
				
		} else if(this.href.indexOf("/album/", 0) > 0) {
			spotifyLinkLength = parseInt(this.href.indexOf("/album/", 0) + 7,10);
			spotifyLinkPrefix= 'spotify:album:';
			spotifyType = 'album';
			
		} else if(this.href.indexOf("/search/", 0) > 0) {
			spotifyLinkLength = parseInt(this.href.indexOf("/search/", 0) + 8,10);
			spotifyLinkPrefix= 'spotify:search:';
			spotifyType = 'search';
		} else {
			return;
		}
		
		jQuery( this ).bind (
			"click",
				function(){
					pageTracker._trackPageview('/outgoing/'+spotifyType+'/' + encodeURIComponent(this.innerHTML));
				}
		);		
		
		this.href = spotifyLinkPrefix + this.href.substr(spotifyLinkLength,this.href.length);
	
	});

	if(jQuery('#createPlaylist').length > 0 ) {
	
			var playlist = '';
			jQuery('#createPlaylist').append("<div id=\"tmpPlaylist\">");

	        jQuery('a.spotify').each(function(i) {

	            if (this.href.indexOf("track", 0) > 0) {
	                playlist = playlist + this.href + ' ';
	            }
	        });


	        jQuery('#tmpPlaylist').html(playlist);
	        jQuery('#tmpPlaylist').css('opacity', 0);

	        jQuery('#createPlaylist').mouseover(function(event) {

	            if (document.selection) {
	                var div = document.body.createTextRange();
	                div.moveToElementText(document.getElementById("tmpPlaylist"));
	                div.select();
	            } else {
	                var div = document.createRange();
	                div.setStartBefore(document.getElementById("tmpPlaylist"));
	                div.setEndAfter(document.getElementById("tmpPlaylist"));
	                window.getSelection().addRange(div);
	            }


	        });

            jQuery('#createPlaylist').mousedown(function(event) {
	            jQuery(this).toggleClass("highlight");
	        });

	        jQuery('#createPlaylist').mouseup(function(event) {
	            jQuery(this).removeClass("highlight");
	        });

	}
});