﻿/* A helper to apply rounded corners to dom boxes. Creates 4 absolutely positioned elements
	with class="corner". Should be styled to a background of four aligned corners where the
	width/height of corner implies where each corner should take its background from.
*/
var Corners = {};
Corners.create = function(el) {
    // We make the parent relative for absolute positioning and also apply hasLayout for IE6
    if (el.getStyle('position') != 'absolute')
        el.setStyle({ position: 'relative', zoom: 1 })

    // Create the basic DOM structure
    var parent = new Element('div', { 'class': 'corners' });
    (4).times(function() { parent.insert(new Element('div', { 'class': 'corner' })) });
    el.insert(parent);
    var corners = parent.select('.corner');

    
    // IE6 only has X/Y versions.
    var bgPos = corners[0].getStyle('backgroundPosition');
    if (bgPos) bgPos = bgPos.split(' ')
    else bgPos = [corners[0].getStyle('backgroundPositionX'), corners[0].getStyle('backgroundPositionY')];
    
    // Collect the basic positioning data needed
    var baseX = parseInt(bgPos[0]);
    var baseY = parseInt(bgPos[1]);
    var dims = corners[0].getDimensions();
    var negBorders = [parseFloat(el.getStyle('borderTopWidth')),
		parseFloat(el.getStyle('borderRightWidth')),
		parseFloat(el.getStyle('borderBottomWidth')),
		parseFloat(el.getStyle('borderLeftWidth'))];
    negBorders = negBorders.map(function(it) { if (isNaN(it)) return 0; else return -Math.round(it); });

    // IE6 messes up right/bottom positioning sometimes, so we'll hard-code it for now.
    if (!window.XMLHttpRequest) {
        var parentDims = el.getDimensions();
        if (parentDims.width % 2)
            negBorders[1] -= 1;
        if (parentDims.height % 2)
            negBorders[2] -= 1;
    }

    corners[0].setStyle({ left: negBorders[3] + 'px', top: negBorders[0] + 'px' });
    corners[1].setStyle({ right: negBorders[1] + 'px', top: negBorders[0] + 'px',
        'backgroundPosition': (baseX - dims.width) + 'px ' + baseY + 'px'
    });
    corners[2].setStyle({ left: negBorders[3] + 'px', bottom: negBorders[2] + 'px',
        'backgroundPosition': baseX + 'px ' + (baseY - dims.height) + 'px'
    });
    corners[3].setStyle({ right: negBorders[1] + 'px', bottom: negBorders[2] + 'px',
        'backgroundPosition': (baseX - dims.width) + 'px ' + (baseY - dims.height) + 'px'
    });
};

/* A Generic bubble/tooltip class. Pass in a target element, content (either html or element) and a options hash:
width: 400			-- the width of the bubble
className: ''		-- the css-class that the bubble should have
autoDestroy: true	-- closes the balloon when the user clicks outside it
pointer: right		-- orientation of pointer, can be 'right', 'left', 'center' and 'hidden'
closeButton: false  -- displays a close button in the bubble
onClosing: null		-- a event handler for when the balloon is closing, can be used to release contained resources.
*/
var Bubble = Class.create({
	initialize: function(target, content, options) {
		if (Bubble.currentBubble != null)
			Bubble.currentBubble.hideBubble();

		this.options = new Hash({ width: 400, className: '', closeButton: false, autoDestroy: true, pointer: 'right', onClosing: null, useScrollingBox: false }).merge(options || {});
		this.target = $(target);
		this.clickFn = this.clicked.bindAsEventListener(this);
		this.parent = $(this.options.get('parent') || Bubble.root);
		this.createBubble(content);
		Bubble.currentBubble = this;
	},

	getRootOffset: function() {
		var valueT = 0, valueL = 0;
		var element = this.target;
		do {
			valueT += element.offsetTop || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
			if (element && (element.tagName.toUpperCase() == 'BODY' || element == this.parent)) {
				break;
			}
		} while (element);
		var result = [valueL, valueT];
		result.left = valueL;
		result.top = valueT;
		return result;
	},

	/* Internal, creates the DOM for the bubble and positions it */
	createBubble: function(content) {
		var template = '<div class="popup #{className}"><div class="pcontent"><div class="t"></div></div><div class="b"><div></div></div></div>';
		this.element = new Element('div', { 'class': 'pwrapper' });
		if (this.options.get('pointer') != 'hidden') {
			this.element.insert(new Element('div', { 'class': 'pointer' }).setStyle({ 'left': (-12 - this.getOffset()) + "px" }));
		}
		this.element.insert(template.interpolate({ 'className': this.options.get('className') }));
		this.element.down('.pcontent').insert(content);

		if (this.options.get('closeButton')) {
			var button = new Element('div', { 'class': 'close' }).observe('click', this.hideBubble.bind(this));
			this.element.down('.pcontent').insert(button);
		}


		/* position it */
		this.parent.insert(this.element);
		var offset = this.getRootOffset();
		var targetDim = this.target.getDimensions();
		this.element.setStyle(
		{
			left: (offset.left + this.getOffset() + targetDim.width / 2) + 'px',
			top: (offset.top + targetDim.height - 1) + 'px',
			width: this.options.get('width') + 'px'
		});

		/* register autodestruction handler */
		if (this.options.get('autoDestroy')) {
			// If we don't wait then the current event that triggered this bubble might close it when it reaches the body.
			setTimeout(function() {
			    $(document.body).observe('click', this.clickFn);

			} .bind(this), 250);

			$('header').observe('mouseover', this.clickFn);
			$('leftsidebar').observe('mouseover', this.clickFn);
			$('mainpagebody').observe('mouseover', this.clickFn);
		}
	},

	getOffset: function() {
		var pointer = this.options.get('pointer');
		if (pointer == 'left')
			return -24;
		else if (pointer == 'right')
			return 24 - this.options.get('width');
		else if (pointer == 'center' || pointer == 'hidden')
			return 0 - this.options.get('width') / 2
	},

	/* Destroyes the bubble and cleans up some resources */
	hideBubble: function() {
		var element = this.element;
		
		element.fade({ duration: 0.0, afterFinish: function() {
				element.remove();
			}
		});
		Bubble.currentBubble = null;
		$(document.body).stopObserving('click', this.clickFn);
		$('header').stopObserving('mouseover', this.clickFn);
		$('leftsidebar').stopObserving('mouseover', this.clickFn);
		$('mainpagebody').stopObserving('mouseover', this.clickFn);

		if (this.options.get('onClosing'))
			this.options.get('onClosing')();

	},

	/* Event handler for when something other than the bubble is clicked, so the bubble should be hidden */
	clicked: function(evt) {
		if (!evt.element().up('div.pwrapper')) {
			this.hideBubble();
		}
	}
});
Bubble.currentBubble = null;
Bubble.root = 'root';

/* Preview player scripts. */
/* Initialize with a target element, and a reference to a Track object that contains information about which track to
play. */
var MiniPlayer = Class.create({
    initialize: function(target, trackid) {
        this.trackid = trackid;
        this.productid = 'T' + trackid;
        this.target = target;
        this.createDom();

        plugin.onPlayPauseChanged = this.onPlayPauseChanged.bind(this);
        plugin.onPlayProgressChanged = this.updateTrack.bind(this);

        var requestPars = { TrackID: this.trackid, CompatibleWith: plugin.pluginName };
        new Ajax.Request('/Ajax/ResolveStreamUrl.ashx', { parameters: requestPars, onSuccess: function(response) {
            plugin.playMedia(response.responseJSON.StreamingUrl);
        }
        });
    },

    createDom: function() {
        //this.silverlightSupport = silverlight;
        var content = new Element("div", { 'class': 'miniplayer' });
        content.insert(new Element("div", { 'class': 'controls' })
			.insert(this.btnPlay = new Element("a", { "class": "play", href: '#' }).update("Spila").observe('click', this.clickPlay.bindAsEventListener(this)))
			.insert(new Element("div", { 'class': 'track' }).update(new Element('div', { 'class': 'handle' }))));
        content.insert(new Element("a", { href: "#", 'class': 'addToPlayer' }).update("Setja í spilara").observe('click', this.clickAddToPlayer.bindAsEventListener(this)));
        content.insert(new Element("a", { href: "#", 'class': 'buyTrack' }).update("Kaupa").observe('click', this.clickBuyTrack.bindAsEventListener(this)));
        this.bubble = new Bubble(this.target, content, { width: 196, onClosing: this.dispose.bind(this), pointer: 'left' });

        this.handle = content.down('.handle');
        this.trackBar = content.down('.track');
        this.slider = new Control.Slider(this.handle, this.trackBar, { range: $R(0, 1), onChange: plugin.setTime.bind(plugin) });
    },

    updateTrack: function(value) {
        if (!this.slider.dragging)
            this.handle.style.left = this.slider.translateToPx(value);
    },

    // Not used at the moment
    loadingTrack: function() {
        var ratio = document.player.GetMaxTimeLoaded() / document.player.GetDuration();
        var xPos = -177 + ratio * this.trackBar.getWidth();
        this.trackBar.setStyle({ 'backgroundPosition': xPos + 'px -42px' });
    },

    clickBuyTrack: function(evt) {
        showToolTip(evt);
        addProductToBasket(this.productid);
        evt.stop();
        this.bubble.hideBubble();
    },

    clickAddToPlayer: function(evt) {
        AddTrackToSilverlightPlayer(this.trackid);
        evt.stop();
        this.bubble.hideBubble();
    },

    clickPlay: function(evt) {
        evt.stop();
        plugin.togglePlayPause();
    },

    onPlayPauseChanged: function(isPlaying) {
        if (isPlaying)
            this.btnPlay.removeClassName("play").addClassName("pause");
        else
            this.btnPlay.removeClassName("pause").addClassName("play");
    },

    dispose: function() {
        plugin.stop();
    }
});


var Tabs = Class.create({
    initialize: function(container) {
        this.container = $(container);
        this.container.select('.tabs a').invoke('observe', 'click', this.switchTabs.bindAsEventListener(this));
    },
    switchTabs: function(evt) {
        var link = evt.element();
        var target = link.getAttribute('rel');
        if (target) {
            this.container.down('.tabs .current').removeClassName('current');
            link.up('li').addClassName('current');

            this.container.down('.section.current').removeClassName('current');
            this.container.down('.section.' + target).addClassName('current');

            if (pageTracker)
                pageTracker._trackEvent("Tabs", "Select", target);

            evt.stop();
        }
    }
});



var SubscriptionTabs = Class.create({
    initialize: function(container, defaultTab, mobileValidatorIDList, creditCardValidatorIDList) {
        this.container = $(container);
        //alert(defaultTab);
        this.defaultTab = defaultTab;
        //this.defaultTab = $(defaultTab);
        var validatorList = mobileValidatorIDList.split('|');
        this.mobileValidators = $A(validatorList);
        validatorList = creditCardValidatorIDList.split('|');
        this.creditCardValidators = $A(validatorList);
        this.container.select('.tabs a').invoke('observe', 'click', this.switchTabs.bindAsEventListener(this));
        if (this.defaultTab != null) {
            var defaultTabRef;
            this.container.select('.tabs a').each(function(tab) {
                var relAttr = tab.getAttribute('rel');
                if (relAttr == defaultTab)
                    defaultTabRef = tab;
            });
            if (defaultTabRef != null)
                this.setTabs(defaultTabRef);
        }
    },
    switchTabs: function(evt) {
        var link = evt.element();
        var loadTab = true;
        if (link.tagName.toLowerCase != 'a')
            loadTab = (!link.up('a').hasClassName('disabled'))
        else
            loadTab = (!link.hasClassName('disabled'))

        if (loadTab)
            this.setTabs(link);
        evt.stop();
    },
    setTabs: function(element) {
        var link = element;
        if (this.container.down('.tabs .current') != null)
            this.container.down('.tabs .current').removeClassName('current');
        link.up('li').addClassName('current');

        var target = link.getAttribute('rel');
        if (target == null)
            target = link.up('a').getAttribute('rel');

        if (pageTracker)
            pageTracker._trackEvent("SubscriptionTabs", "Select", target);

        var selectedRadioButtons = [];
        this.container.select('.' + target + ' .selection input[@type=\"radio\"]').each(function(radioButton) {
            if (radioButton.checked)
                selectedRadioButtons.push(radioButton);
        });

        this.togglePaymentMethod(selectedRadioButtons[0].up('span'));

        this.container.down('.currentSubType').value = selectedRadioButtons[0].value;
        this.container.down('.currentSubRouteType').value = target;

        this.container.select('.' + target + ' .selection span').invoke('observe', 'click', this.chooseSubTypeObserver.bindAsEventListener(this, target));
        this.container.select('.' + target + ' .selection span input').invoke('observe', 'click', this.chooseSubTypeObserver.bindAsEventListener(this, target));

        this.chooseSubType(selectedRadioButtons[0], target, false);

        this.container.down('.section.current').removeClassName('current');
        this.container.down('.section.' + target).addClassName('current');
    },
    chooseSubTypeObserver: function(evt, target) {
        this.chooseSubType(evt.element(), target, true);
    },
    chooseSubType: function(element, target, doPaymentToggle) {
        var item = element;

        var titleAttr = item.getAttribute('title');

        if (titleAttr == null || titleAttr == '') {
            if (doPaymentToggle)
                this.togglePaymentMethod(item.up('span'));
            titleAttr = item.up('span').getAttribute('title');
        }
        else {
            if (doPaymentToggle)
                this.togglePaymentMethod(item);
        }

        var titleArray = titleAttr.split('|');

        var price = titleArray[1];
        var subType = titleArray[0];
        var subTypeConstant = titleArray[2];

        this.container.down('.currentSubType').value = subTypeConstant;
        this.container.down('.' + target + ' .phPrice').innerHTML = '' + price + ',-';
        this.container.down('.' + target + ' .subtypename').innerHTML = ' - ' + subType;
    },
    togglePaymentMethod: function(element) {
        this.creditCardForm = $('creditcardform');
        this.mobileForm = $('mobilepaymentform');
        if (element.hasClassName('mobileform')) {
            if (this.creditCardForm != null) {
                this.creditCardForm.removeClassName('hide');
                this.creditCardForm.addClassName('hide');
            }
            if (this.mobileForm != null)
                this.mobileForm.removeClassName('hide');

            this.creditCardValidators.each(function(validator) {
                ValidatorEnable($(validator), false);
            });
            this.mobileValidators.each(function(validator) {
                var validatorItem = $(validator);
                if (validatorItem.style.display == 'none')
                    ValidatorEnable(validatorItem, true);
            });
        }
        else {
            if (this.creditCardForm != null)
                this.creditCardForm.removeClassName('hide');
            if (this.mobileForm != null) {
                this.mobileForm.removeClassName('hide');
                this.mobileForm.addClassName('hide');
            }

            this.mobileValidators.each(function(validator) {
                ValidatorEnable($(validator), false);
            });

            this.creditCardValidators.each(function(validator) {
                var validatorItem = $(validator);
                if (validatorItem.style.display == 'none')
                    ValidatorEnable($(validator), true);
            });
        }
        if (element.hasClassName('free')) {
            this.creditCardForm.addClassName('free');
            this.mobileForm.addClassName('free');
        }
        else {
            this.creditCardForm.removeClassName('free');
            this.mobileForm.removeClassName('free');
        }
    }
});


/* A Generic spinner class for floated list of elements. Inserts back/forward buttons and applies
paging on elements that are not visible.
*/

var Spinner = Class.create({
    initialize: function(target, itemsInView) {
        this.targetId = target;
        target = $(target);

        this.items = target.childElements();
        this.itemsInView = itemsInView;
        this.currentPage = 0;
        this.pageCount = Math.ceil(this.items.length / this.itemsInView);
        this.updateVisibility();

        if (this.items.length > this.itemsInView) {
            var parent = target.up();
            parent.insert(new Element('span', { 'class': 'back' }).observe('click', this.lastPage.bind(this)));
            parent.insert(new Element('span', { 'class': 'next' }).observe('click', this.nextPage.bind(this)));
        }
    },

    lastPage: function() {
        if (this.pageCount <= 1) return;
        this.currentPage -= 1;
        if (this.currentPage < 0) this.currentPage = this.pageCount - 1;
        this.updateVisibility();
        if (pageTracker)
            pageTracker._trackEvent("Spinner", "LastPage", this.targetId);
    },

    nextPage: function() {
        if (this.pageCount <= 1) return;
        this.currentPage += 1;
        if (this.currentPage >= this.pageCount) this.currentPage = 0;
        this.updateVisibility();
        if (pageTracker)
            pageTracker._trackEvent("Spinner", "NextPage", this.targetId);
    },

    updateVisibility: function() {
        var start = this.currentPage * this.itemsInView;
        var end = start + this.itemsInView;
        this.items.each(function(el, i) {
            if (i >= start && i < end)
                el.show();
            else
                el.hide();
        });
    }
});

var AjaxSpinner = Class.create({
    initialize: function(target, itemsInView, url, ajaxKey, maxAvailableAjaxItems) {
        this.targetId = target;
        target = $(target);

        this.items = target.childElements();
        this.itemsInView = itemsInView;
        this.maxAvailableAjaxItems = maxAvailableAjaxItems;
        this.ajaxUrl = url;
        this.ajaxKey = ajaxKey;
        this.currentPage = 0;
        this.pageCount = Math.ceil((this.items.length + this.maxAvailableAjaxItems) / this.itemsInView);
        this.cache = mainRequestCache;

        if ((this.items.length + this.maxAvailableAjaxItems) > this.itemsInView) {
            var parent = target.up();
            parent.insert(new Element('span', { 'class': 'back' }).observe('click', this.lastPage.bind(this)));
            parent.insert(new Element('span', { 'class': 'next' }).observe('click', this.nextPage.bind(this)));
        }
    },

    lastPage: function() {
        if (this.pageCount <= 1) return;
        this.currentPage -= 1;
        if (this.currentPage < 0) this.currentPage = this.pageCount - 1;
        this.fetchPage();
        if (pageTracker)
            pageTracker._trackEvent("Spinner", "LastPage", this.targetId);
    },

    nextPage: function() {
        if (this.pageCount <= 1) return;
        this.currentPage += 1;
        if (this.currentPage >= this.pageCount) this.currentPage = 0;
        this.fetchPage();
        if (pageTracker)
            pageTracker._trackEvent("Spinner", "NextPage", this.targetId);
    },

    fetchPage: function() {
        var requestPars = { Page: this.currentPage, Key: this.ajaxKey, Type: 'Spinner', ItemsPerPage: this.itemsInView };
        this.cache.fetch(this.ajaxUrl, requestPars, function(response) {
            var htmlComplete = "";
            var template = "<li><a href='#{AlbumUrl}' title='#{AlbumName}' class='albumProduct'><img src='#{AlbumImageUrl}' alt='#{AuthorName} - #{AlbumName}'></a>";
            template += "<a href='#{AlbumUrl}'><strong>#{DisplayAlbumName}</strong></a>";
            template += "<a href='#{AuthorUrl}'>#{DisplayAuthorName}</a></li>";
            if (response.responseJSON) {
                response.responseJSON.SpinnerList.each(function(record, index) {
                    var extra = {
                        DisplayAlbumName: Utility.TruncateString(record.AlbumName, 15),
                        DisplayAuthorName: Utility.TruncateString(record.AuthorName, 15)
                    };
                    var html = template.interpolate(Object.extend(record, extra));
                    htmlComplete += html;
                });
            }
            $(this.targetId).innerHTML = htmlComplete;
        } .bind(this));
    }
});

var PopularArtists = Class.create({
    initialize: function(container) {
        this.container = $(container);
        this.cache = mainRequestCache;
        this.mousedOverChar = '';
        this.container.select('a').invoke('observe', 'mouseout', this.clearMousedOverChar.bindAsEventListener(this));
        this.container.select('a').invoke('observe', 'mouseover', this.ajaxCall.bindAsEventListener(this));
    },
    clearMousedOverChar: function() {
        this.mousedOverChar = '';
    },
    ajaxCall: function(evt) {
        var requestPars = { Letter: evt.target.innerHTML, Type: 'Author' };
        this.mousedOverChar = evt.target.innerHTML.charAt(0);
        this.cache.fetch('/Ajax/Popularity.ashx', requestPars, function(response) {
            var htmlComplete = "";
            var template = "<a href='#{AuthorUrl}' title='#{AuthorName}'>#{DisplayAuthorName}</a><br />";
            if (response.responseJSON) {
                response.responseJSON.AuthorList.each(function(record, index) {
                    var extra = {
                        DisplayAuthorName: Utility.TruncateString(record.AuthorName, 25),
                        DisplayAlbums: PopularArtistAlbums,
                        DisplaySongs: PopularArtistSongs
                    };
                    var html = template.interpolate(Object.extend(record, extra));
                    htmlComplete += html;
                });
                this.loadBubble.bind(this).delay(0.3, evt, htmlComplete, response.responseJSON.SearchKey);
            }
        } .bind(this));
    },
    loadBubble: function(evt, html, hoverkey) {
        if (this.mousedOverChar != hoverkey) {
            return;
        }
        if (html != "") {
            html += "<a href='" + evt.target.href + "' class='morelink'>" + ViewMore + "</a>";
            var bubbleOption = { width: 200, pointer: 'center', className: 'popularartists' };
            var location = CheckAlphaLocation(evt.target.innerHTML);
            if (location == 0) bubbleOption.pointer = 'left';
            else if (location == 2) bubbleOption.pointer = 'right';
            new Bubble(evt.target, html, bubbleOption);
        }
    }
});

function CheckAlphaLocation(str) {
    var itemlist = 'A Á B C'.split(' ');
    for (var i = 0; i < itemlist.length; i++) { if (str.toUpperCase().charAt(0) == itemlist[i]) return 0; }
    itemlist = 'Þ Æ Ö 0'.split(' ');
    for (var i = 0; i < itemlist.length; i++) { if (str.toUpperCase().charAt(0) == itemlist[i]) return 2; }
    return 1;
}

function ApplyCustomBalloons(element, setTitle, options, replaceType) {
    $$(element).each(function(el) {
        var title = '';
        
        if (setTitle != '')
            title = setTitle
        else {
            if (replaceType == 1)
                title = el.title.replace(' - ', '<br />');
            else
                title = el.title.replace(/{komma}/g, '\'');
        }
        el.title = '';
        el.observe('click', function(ev) {
            ev.stop();
            new Bubble(el, title, options);
        });
    });
}


function openCustomPopUp(url, title, left, top, width, height, toolbar, resizeable) {
    window.open(url, title, 'left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',toolbar=' + toolbar + ',resizable=' + resizeable);
    return;
}

//Shows or hide the play pause button
function playTrackByTrackID(e, tid) {
	new MiniPlayer(e, tid);
}

//Ajax sheitein
function waitForResponse(response) {
	try {
		xmlResponse = response.responseXML;
		//alert(xmlResponse.xml);
		if (xmlResponse.getElementsByTagName("reply")[0].childNodes[0].nodeValue == "3")
			alert(CantBuyThatTrack);
		//Do something with the response
		replytxt = xmlResponse.getElementsByTagName("replytxt")[0].childNodes[0].nodeValue;

		layer = xmlResponse.getElementsByTagName("layer");
		layername = layer.length > 0 ? layer[0].childNodes[0].nodeValue : null;

		if (replytxt != null && layername != null) {
			//Write reply into shopping cart
			var replyElement = document.getElementById(layername);
			if (replyElement == null || replyElement == "")
			    replyElement = window.opener.document.getElementById(layername);
			if (replyElement) {
				replyElement.innerHTML = replytxt;
			}
			if (layername != null && layername == "shopping_cart_total") {

				setSuccessTimeOutBasket("500");
				displayBasketTip();

				var regex = /\((\d+)\)/;
				var match = regex.exec(replytxt);
				var cartCount = parseInt(match[1]);

				// This is used by our client to check the status of the basket.
				var txtBasket = $('txtBasketStatus');
				if (txtBasket) {
				    txtBasket.value = cartCount;

					if (txtBasket.fireEvent)
					    txtBasket.fireEvent('onchange', document.createEventObject());

				}

				// Notify the Mac client about the cart status.
				try {
				    window.TonlistClient.updateCartCount_(cartCount);
				} catch (err) { }
			}
		}
	}
	catch (e) {
		//trace("waitForResponse error:" + e.description);
	}
}

function postData(requestUrl, data, callback) {
	new Ajax.Request(requestUrl, { parameters: data, onSuccess: callback || waitForResponse });
}

function displayBasketTip() {
	// Check in our cookies to see if this tip has been displayed before.
	if (document.cookie.indexOf('SeenBasketTip') > -1)
		return;
	if (!$('shopping_cart_total'))
		return;

	new Bubble('shopping_cart_total', '<h1>Hlut bætt í körfuna</h1><p>Smelltu á flipann Karfa til að ljúka við kaupin eða haltu áfram að bæta í hana.</p>', { width: 200 });

	$(document.body).scrollTo();

	// Save to cookie that we've seen this before.
	var expiration = (new Date((new Date()).getTime() + 3600000 * 24 * 365)).toGMTString();
	document.cookie = 'SeenBasketTip=true; path=/; expires=' + expiration;
}
// --------
// Initialize values for the cart popup (single album/track buy)
// --------
function setAlbumListPopupValues(albumPrice, albumName, isInCart, imgSrc) {

    var elAlbumHeadline = document.getElementById('lblAlbumCartPopupHeadline');
    var elAlbumPrice = document.getElementById('lblPopupAlbumPrice');
    var elAlbumName = document.getElementById('lblPopupAlbumName');
    var elCartAlbumStatus = document.getElementById('lblAlbumCartItemStatus');
    var elImgSrc = document.getElementById('imgAlbumListCoverSmall');

    if (elImgSrc) {
        elImgSrc.setAttribute("src", imgSrc);

    }
    if (elAlbumHeadline) {
        elAlbumHeadline.innerHTML = albumName;
    }

    if (elAlbumPrice) {
        elAlbumPrice.innerHTML = AlbumPrice + ": " + albumPrice;
    }

    if (elAlbumName) {
        elAlbumName.innerHTML = "<b>" + albumName + "</b>";
    }

    if (isInCart == 1) {

        if (elCartAlbumStatus)
            elCartAlbumStatus.innerHTML = AlreadyInBasket + "..";
        if (elAlbumHeadline)
            elAlbumHeadline.innerHTML += " " + AlreadyInBasket;
        if (elAlbumPrice)
            elAlbumPrice.innerHTML = "";

    }
    else {
        if (elCartAlbumStatus)
            elCartAlbumStatus.innerHTML = HasBeenPutInBasket;
        if (elAlbumHeadline)
            elAlbumHeadline.innerHTML += " " + PutInBasket;
    }

    jQuery.facebox({ div: '#albumlistcart' });

}

function setCartPopupValues(trackPrice, trackName, albumName, isInCart) {

    var elTrackHeadline = document.getElementById('lblCartPopupHeadline');
    var elTrackPrice = document.getElementById('lblPopupTrackPrice');
    var elTrackName = document.getElementById('lblPopupTrackName');
    var elCartTrackStatus = document.getElementById('lblCartItemStatus');
  

    if (elTrackHeadline) {
        elTrackHeadline.innerHTML = trackName;
    }

    if (elTrackPrice) {
        elTrackPrice.innerHTML = AlbumPrice + ": " + trackPrice;
    }

    if (elTrackName) {
        elTrackName.innerHTML = "<b>" + trackName + "</b>" + "<br />(" + FromTheAlbum + " " + albumName + ")";
    }

    if (isInCart==1) {

        if (elCartTrackStatus)
            elCartTrackStatus.innerHTML = AlreadyInBasket + "..";
        if (elTrackHeadline)
            elTrackHeadline.innerHTML += " " + AlreadyInBasket;
        if (elTrackPrice)
            elTrackPrice.innerHTML = "";

    }
    else {
        if (elCartTrackStatus)
            elCartTrackStatus.innerHTML = HasBeenPutInBasket
        if (elTrackHeadline)
            elTrackHeadline.innerHTML += " " + PutInBasket;   
    }   
    jQuery.facebox({ div: '#track_cart' });
}

//
// Initialize values for the cart popup (single album/track buy) 
//
function setCartPopupMultipleTracksValues(count) {
    
    var elTrackHeadline = document.getElementById('lblCartPopupHeadline');
    var elTrackPrice = document.getElementById('lblPopupTrackPrice');
    var elTrackName = document.getElementById('lblPopupTrackName');
    var elCartTrackStatus = document.getElementById('lblCartItemStatus');
   

    if (elTrackHeadline) {
        elTrackHeadline.innerHTML = count + " " + SongsPutInBasket;
    }
    if (elCartTrackStatus)
        elCartTrackStatus.innerHTML = "";
    if (elTrackPrice)
        elTrackPrice.innerHTML = "";

    if (elTrackName) {
        
        if (count == 1)
            elTrackName.innerHTML = "<b>" + count + "</b>" + " " + SingleSongPutInBasket;
        else if (count > 1)
            elTrackName.innerHTML = "<b>" + count + "</b>" + " " + SongsPutInBasket;
        
    }
    jQuery.facebox({ div: '#track_cart' });
}

function addProductToBasket(productID) {
    if (pageTracker)
        pageTracker._trackEvent("Basket", "Add", productID);

	// Add product to basket
	postData("/Ajax/BasketService.ashx", "a=addProduct&id=" + productID);
}

function removeProductFromBasket(productID) {
    if (pageTracker)
        pageTracker._trackEvent("Basket", "Remove", productID);
    // Add track to playlist
	postData("/Ajax/BasketService.ashx", "a=removeProduct&id=" + productID);
}

function rateAlbum(albumID, rating, id) {
    // Give the album a rating
    var obj = document.getElementById(id);
    obj.className = "myRating";
    obj.style.width = (rating * 20) + '%';
    
   
	postData("/Ajax/RatingService.ashx", "a=rateAlbum&id=" + albumID + "&rating=" + rating);
}

function GetOtherStreamedAlbums(albumID, months, insideIceland) {
   // var requestPars = { AlbumID: albumID, Months: months, InsideIceland: insideIceland };
   // alert("javascript called with: albumId: " + albumID + "'n months: " + months);
    
   // this.cache.fetch('/Ajax/OtherStreamedAlbums.ashx', requestPars, function(response) 
    //postData("/Ajax/OtherStreamedAlbums.ashx", "AlbumID=" + albumID + "&Months=" + months + "&InsideIceland=" + insideIceland);
}

function giveAlbumRatingReview(objname, previewer, nvalue) {
	document.getElementById(objname).value = nvalue;
	document.getElementById(previewer).style.width = (nvalue * 20) + '%';
}

function CheckAllClick(strChkAllBoxId, strPrefix) {
	var mainCheckBox = $(strChkAllBoxId);
	var checkBoxArray = $$('input[id$=' + strPrefix + '][type=checkbox]');

	checkBoxArray.each(function(box) { if(!box.disabled) box.checked = mainCheckBox.checked; });
}

var toggleDivLocked = false;
function toogleDivBlind(id) {
	if ($(id).style.display == 'none' && !toggleDivLocked) {
		toggleDivLocked = true;
		new Effect.BlindDown(id, { afterFinish: unlockToggleDiv });
	}
	else if (!toggleDivLocked) {
		toggleDivLocked = true;
		new Effect.BlindUp(id, { afterFinish: unlockToggleDiv });
	}
	return false;
}
function unlockToggleDiv() {
	toggleDivLocked = false;
}

function CreateNewPopupSpecific(url, width, height) {
	newwindow = window.open(url, 'Other', 'height=' + height + ',width=' + width + ',alwaysRaised=1,dependant=1');
	if (!newwindow.opener) newwindow.opener = self;
}

function CreateNewPopupSpecificWithScrollbar(url, width, height) {
	newwindow = window.open(url, 'Other', 'height=' + height + ',width=' + width + ',alwaysRaised=1,dependant=1,scrollbars=1');
	if (!newwindow.opener) newwindow.opener = self;
}

function GetCheckedTracks(strPrefix) {
	var checkBoxArray = $$('input[id$=' + strPrefix + '][type=checkbox]');
	var tracks = [];
	checkBoxArray.each(function(box, i) {
	    if (box.checked) {
	        tracks.push(box.value);
	    }
	});
	return tracks;
}

function CheckBoxAddTracksToSilverlightPlayer(strPrefix, append) {
    var selectedTracks = GetCheckedTracks(strPrefix);
    if (selectedTracks.length > 0) {
        var trackIDList = '';
        selectedTracks.each(function(item, i) {
            if (trackIDList != '')
                trackIDList += ';';
            trackIDList += item;
        });
        AddTrackListToSilverlightPlayer(trackIDList, append);
    }
    else {
        alert(NoSongsInList);
    }
}

function AddTracksToPlaylist(strPrefix, playlistid) {
	var selectedTracks = GetCheckedTracks(strPrefix);

	if (selectedTracks.length > 0) {
		var querystring = '';
		selectedTracks.each(function(track) {
			querystring += track + ',';
		});
		postData("/Ajax/PlaylistService.ashx", "pid=" + playlistid + "&a=addTracks&ids=" + querystring);
	}
	else {
	    alert(NoSongsHaveBeenChosen);
	    
	}
}

function CreatePlaylistWithTracks(tracks, handler) {
	if (tracks.length > 0) {
		var name = prompt(PromptPlaylistName)
		while (name == "")
			name = prompt(PlaylistMissingName);
		if (name == null)
			return false;

		var querystring = '';
		tracks.each(function(track) {
			querystring += track + ',';
		});
		postData("/Ajax/PlaylistService.ashx", "a=createPlaylistWithTracks&v=" + name + "&ids=" + querystring, function(resp) {
			var success = resp.responseXML.getElementsByTagName("reply")[0].childNodes[0].nodeValue;
			if (success != "1")
				return;
			var id = resp.responseXML.getElementsByTagName("replytxt")[0].childNodes[0].nodeValue;

			try {
				$$('.js-trackactions').invoke('add', new Option(name, id), null);
			}
			catch (e) { //in IE, try the below version instead of add()
				$$('.js-trackactions').invoke('add', new Option(name, id));
			}
			if (handler)
				handler(id, name);
		});
	}
	else {
		alert(NoSongsHaveBeenChosen);
		return false;
	}
	return true;
}

function AddPlayerTracksToBasket(selectedTracks) {
	if (selectedTracks.length > 0) {
		var querystring = '';
		selectedTracks.each(function(track) {
			querystring += track.ProductID + ',';
		});

		postData("/Ajax/BasketService.ashx", "a=addProducts&id=" + querystring);
		return true;
	}
	else {
		alert(NoSongsHaveBeenChosen);
		return false;
	}
}

function AddTracksToBasket(strPrefix) {
    var selectedTracks = GetCheckedTracks(strPrefix);
   
	if (selectedTracks.length > 0) {
		var querystring = '';
		selectedTracks.each(function(track) {
		    querystring += 'T' + track + ',';
		});

		//Add the tracks from the checkbox to the cart-popup
		setCartPopupMultipleTracksValues(selectedTracks.length);    
		postData("/Ajax/BasketService.ashx", "a=addProducts&id=" + querystring);
	}
	else {
	    alert(NoSongsHaveBeenChosen);
	}
}

function showToolTip(e) {
    if (document.all) e = event;
    var text = 'B&aelig;ti v&ouml;ru &iacute; k&ouml;rfu <img src=\'../images/indicator_white.gif\'>';
    var obj = document.getElementById('basket_tooltip');
    if (obj == null || obj == "")
        obj = window.opener.document.getElementById('basket_tooltip');
    //var obj2 = document.getElementById('basket_tooltip_content');
    //obj2.innerHTML = text;
    obj.style.display = 'block';
    var st = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
    if (navigator.userAgent.toLowerCase().indexOf('safari') >= 0) st = 0;
    var leftPos = e.clientX - 100;
    if (leftPos < 0) leftPos = 0;
    obj.style.left = leftPos + 'px';
    obj.style.top = e.clientY - obj.offsetHeight - 1 + st + 'px';

    //Start timeout to put into basket
    window.setTimeout("onTimer(" + 1 + ")", 5000);
}

function hideToolTip() {
    var obj = document.getElementById('basket_tooltip');
    if (obj == null || obj == "")
	    obj = window.opener.document.getElementById('basket_tooltip');
	obj.style.display = 'none';
}

var elapse = 1000; // this is interval - 1000 millisecond
var timer = null;
var done = false;
function onTimer(i) {
	if (done) return;
	// stop it when the function run over 5000 millisecond
	if (i >= 3) {
		timer = null;
		//here uncheck the live check and post form
		hideToolTip();
		return;
	}

	i++;
	timer = window.setTimeout("onTimer(" + i + ")", elapse);
}

//Hides the basket balloon after the time specified
function setSuccessTimeOutBasket(elapse) {
	done = true;
	window.setTimeout("hideToolTip()", elapse);
}

// Apply some global behaviours using css class names.
//Event.observe(document, 'dom:loaded', function() { //This method is broken DO NOT USE THIS OR FEEL THE WRATH OF DAVID!!!!!
Event.observe(window, 'load', function() {

    //$j(document).ready(function() {
        var itemList = $j('a.load-local');
        if (itemList.length > 0) {
            $j('a.load-local').cluetip({
                local: true, // use the invoking element's title attribute to populate the clueTip...
                // ...and split the contents into separate divs where there is a "|"
                hideLocal: true, // hide the clueTip's heading
                sticky: true,
                activation: 'click',
                arrows: false,
                closeText: 'Loka',
                positionBy: 'mouse',
                leftOffset: -15,
                topOffset: -15,
                cluetipClass: 'rounded js-corners',
                width: 190,
                dropShadow: false,
                mouseOutClose: true,
                showTitle: false,
                delayedClose: 15000,
                closePosition: 'title'
            });
        }
    //});

    $$('.albumMatrix li a').each(function(el) {
        if (!el.hasClassName('albumProduct')) {
            if (el.innerHTML.stripTags().length > 15) {
                el.writeAttribute('title', el.innerHTML.stripTags());
                if (el.down())
                    el.innerHTML = '<strong>' + el.innerHTML.stripTags().substring(0, 15) + '...</strong>';
                else
                    el.innerHTML = el.innerHTML.substring(0, 15) + '...';
            }
        }
    });

    ApplyCustomBalloons('a.trackInfo', '', { width: 200 }, 1);
    ApplyCustomBalloons('a.sharelist', '', { width: 120 }, 2);
    ApplyCustomBalloons('a.bubblebox', PlaylistNotAvailable, { width: 250 }, 2);
    //ApplyCustomBalloons('span.buy', { width: 120, parent: 'tracklistParent' }, 2);

    $$('.js-add-last > :last-child').invoke('addClassName', 'last');

    $$('.js-autoblur').each(function(it) {
        it.focusString = it.getValue();
        it.observe('focus', function() { if (this.getValue() == this.focusString) this.clear(); });
        it.observe('blur', function() { if (this.getValue() == '') this.value = this.focusString; });
        if (document.activeElement == it) it.clear();
    });

    if (Prototype.Browser.IE) { // Ofcourse IE does not support anything!
        $$('.js-corners').each(function(el) { Corners.create(el); });

        $$('.js-autohover').each(function(el) {
            el.observe("mouseover", function() { el.setStyle({ 'opacity': 0.85 }); })
        .observe("mouseout", function() { el.setStyle({ 'opacity': 1.0 }); });
        });
    }

    $$('.js-add-oddeven').each(function(it) {
        it.childElements().each(function(child, i) { child.addClassName(i % 2 ? 'even' : 'odd'); });
    });

    $$('.js-drm').each(function(el) { el.setAttribute("title", DrmMessage); });  //Title on an image... well anyway "setAttribute" does not work well in IE.

    $$('.js-trackactions').each(function(it) {
        it.observe("change", function(event) {
            var curItem = it.options[it.selectedIndex].value;
            var success = true;
            var no_popup = true;
            if (curItem == "__default") return;
            else if (curItem == "__play") {
                success = CheckBoxAddTracksToSilverlightPlayer("TrackListItem", true);
            }
            else if (curItem == "__playnext") {
                success = CheckBoxAddTracksToSilverlightPlayer("TrackListItem", false);
            }
            else if (curItem == "__silverlight_play") {
                success = CheckBoxAddTracksToSilverlightPlayer("TrackListItem", true);
            }
            else if (curItem == "__buy") {
                showToolTip(event);
                no_popup = false;
                AddTracksToBasket("TrackListItem");
            }
            else if (curItem == "__new") {
                success = CreatePlaylistWithTracks(GetCheckedTracks('TrackListItem'));
            }
            else if (curItem == "__disabled") {
                success = false;
            }
            else {
                AddTracksToPlaylist('TrackListItem', parseInt(curItem));
            }

            if (GetCheckedTracks("TrackListItem").length > 0) {
                if (success && no_popup) {
                    element = new Element("div").update('<div class="box js-corners" style="background-color:#efefef; text-shadow: #fff 0 1px 1px; padding: 5px; text-align:center; border:1px solid #cfcfcf; width:100px; -moz-border-radius: 5px; -webkit-border-radius: 5px; ">' + ActionPerformed + '</div>');

                    it.insert({ after: element });

                    new Effect.Fade(element, { delay: 4, from: 1, to: 0, duration: 5 });
                }
            }

            it.selectedIndex = 0;
        });
    });

    $$('.js-tracklist').each(function(it) {
        it.observe("change", function(event) {
            var curItem = it.options[it.selectedIndex].value;
            var success = true;
            window.location = "/Music/ChartList.aspx?ID=" + curItem;
        });
    });

    $$('.js-tabs').each(function(el) { new Tabs(el); });

    $$('.js-format').each(function(it) {
        it.observe("change", function(event) {
            var curRow = it.up('tr');
            var value = it.getValue();
            curRow = curRow.next('tr');
            while (curRow != null && curRow.hasClassName('album') == false) {
                var btnDl = curRow.down('.btnDownload');
                if (btnDl != null) {
                    btnDl.href = btnDl.href.replace((/FormatID=[0-9]+/i), "FormatID=" + value);
                }
                curRow = curRow.next('tr');
            }
        });
    });

    /* Automatically clears rows of floated lists. 
    If each item in the list has dynamic height, then a new row of items 
    might start in the wrong place. If that happens, use this */
    $$('.js-autoclear').each(function(el) {
        var children = el.childElements();
        var parentWidth = el.getWidth();
        var offset = 0;
        children.each(function(child) {
            var childWidth = child.getWidth();
            if (offset + childWidth > parentWidth) {
                child.insert({ before: '<div style="clear: both"></div>' });
                offset = 0;
            }
            offset += childWidth;
        });
    });

    new PopularArtists('alphabet');
});

function FixString(itemID) {
    var matchTag = /<(?:.|\s)*?>/g;
    $(itemID).value = $(itemID).value.replace(matchTag, "");
    return true;
}


/* MP3 progressive player code */
//Shows or hide the play pause button
function doImgButton(e, tid, url, type) {
    //$j("#minititle").html(e.title);
    $j("#miniaddplayer").attr('title', tid);
    $j("#minibuytrack").attr('title', tid);

    $j("#extraInfoNoStream").hide();
    $j("#extraInfoUpgrade").hide();
    if (type==1) {
        $j("#extraInfoUpgrade").show();
    }
    else if (type==2) {
        $j("#extraInfoNoStream").show();
    }
    
	// For compatibility, please remove ASAP
	var wasPlaying = e.alt == "Pause";

	putAllImgButtonsOnPlay();
	if (wasPlaying) {
		pausemovie();
	} else {
		e.src = "/images/icon-pause.png";
		e.alt = "Pause";
		playmovie(url);
	}
}

//Play movie
function playmovie(tid) {
    //thisMovie("tonlistfl").SetVariable("file", "http://dev.m.tonlist.is/30sec/2/02183057.mp3");
    ////url = "http://dev.m.tonlist.is/30sec/1/0" + tid.substring(0,tid.length-2)+"0"+ "0.mp3";
    getFlashMovieObject("tonlistfl").sendEvent('LOAD', tid);
    //alert(url);
    getFlashMovieObject("tonlistfl").sendEvent('PLAY');
    //.flAlert(tid);

}

//Pauses the flash movie
function pausemovie() {
    //thisMovie("tonlistfl").SetVariable("file", "");
    getFlashMovieObject("tonlistfl").sendEvent('PLAY');
    //.flStop("");
}

function getFlashMovieObject(movieName) {
    if (document.embeds[movieName])
        return document.embeds[movieName];
    if (window.document[movieName])
        return window.document[movieName];
    if (window[movieName])
        return window[movieName];
    if (document[movieName])
        return document[movieName];
    return null;
}

//Gets the name of current movie
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        //window[movieName] = document.forms[0].[movieName] ;
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

//Puts all pause icons back to play
function putAllImgButtonsOnPlay() {
    $$('a.load-local').each(function(e) { if (e.alt == "Pause") { e.alt = 'Play'; e.src = '/images/icon-play.png'; } });
};

/* MP3 progressive player code end */