/**
 * Voordat default.js geinclude wordt, moet jquery eerst geinclude zijn in de pagina 
*/

// JQuery & prototype gaan niet goed samen, daarom dit
var $j = jQuery.noConflict();
var defaultSearchText = 'Trefwoord(en)';

/**
* 1: defaults
* 2: ajax functionaliteit
* 3: exitlog
**/
////////////////////////////////////////////////////////////   DEFAULTS

// loginbox tonen/verbergen
function toggleLogin()
{
    if ($j('#loginBox').is(':visible') ) {
        // verbergen
        $j('#loginBox').hide();
        $j('#btnLogin').removeClass('selected');
        $j('#btnLogin').html('Inloggen');
    } else {
        // tonen
        $j('#loginBox').show();
        $j('#btnLogin').addClass('selected');
        $j('#btnLogin').html('Inloggen x');
    }
}

$j(document).ready(function()
{
    // Zoekvelden
    $j('.searchInput').each( 
        function(index)
        {
            if ($j(this).val() == '')
            {
                $j(this).val(defaultSearchText).addClass('blur');
            }
            
            $j(this).focus(function() 
            { 
                if ($j(this).val() == defaultSearchText)
                {
                    $j(this).val('').removeClass('blur');
                }
            });
            
            $j(this).blur(function()
            {
                if ($j(this).val() == '')
                {
                    $j(this).val(defaultSearchText).addClass('blur');
                } 
            });
        }
    );
        
    
    // LoginBox
    var mouse_is_inside = false;
    
    $j("#loginBox").mouseover(function(e){
        mouse_is_inside = true;
        e.stopPropagation();
    }).mouseout(function(e){
        mouse_is_inside = false;
        e.stopPropagation();
    });
     
    $j(document).mouseup(function(){ 
        if( ! mouse_is_inside) 
        {
            $j('#loginBox').hide();
            $j('#btnLogin').removeClass('selected');
            $j('#btnLogin').html('Inloggen');
        }
    });
    
    $j('#btnLogin').hover(function(){ 
        mouse_is_inside = true; 
    }, function(){ 
        mouse_is_inside = false; 
    });
    
    
    // OUE headers
    $j('#oue .header').each(function(index, el)
    {
        var list = $j(this).next('ul');
        if (!list) return false;
        
        $j(this).click(function() {
            $j(list).slideToggle(100); 
            $j(this).toggleClass('open');
            return false;
        });
    });

    $j('.list_more').each(function(index, el)
    {
        var more = $j(this).next('ul');
        $j(this).click(function() {
            $j(more).slideToggle(100); 
            $j(this).toggleClass('open');
            return false;
        });
        
    });
    
});

function checkSearch(searchInput)
{
    if (searchInput.value == defaultSearchText)
    {
        searchInput.value = '';
    }
    return true;
}

// 
/**
 * Opent mp3player.php met get argumenten.
 *
 * Bij meerdere argumenten worden deze samengevoegd zodat bijvoorbeeld een bepaalde artiest en een aantal
 * aparte files wordt afgespeeld.
 *
 * @param  mixed   artistIds	 Ids van artiest(en) (array van ints, string van kommagescheiden ints of int)
 * @param  int     playId	     Id van als eerste af te spelen bestand
 * @param  bool    defaultFiles  Slechts 1 nummer per artiest, namelijk alleen de als default ingestelde file
 * @param  mixed   fileIds 	     Ids van de file(s) (array van ints, string van kommagescheiden ints of int)
 * @param  object  extraOptions	 Extra opties: Nu nog alleen sort
 * @return void
 */
 
function openMusicPlayer(artistIds, playId, defaultFiles, fileIds, extraOptions)
{
    var reqString;

    if (typeof artistIds == 'array') {
        artistIds = artistIds.join(',');
    }
    if (typeof fileIds == 'array') {
        fileIds = artistIds.join(',');
    }

    if (defaultFiles) {
        reqString = 'default=1';
    } else {
        reqString = 'default=0';
    }

    if (artistIds) {
        reqString += '&artistIds=' + artistIds;
    }
    if (fileIds) {
        reqString += '&fileIds=' + fileIds;
    }
    if (playId) {
        reqString += '&playId=' + playId;
    }
	if (extraOptions) {
		if (extraOptions.chart) {
			reqString += '&chart=' + extraOptions.chart;
		}
		if (extraOptions.allFiles) {
			reqString += '&showAllArtistFiles=' + extraOptions.allFiles;
		}
		if (extraOptions.releaseId) {
			reqString += '&releaseId=' + extraOptions.releaseId;
		}
	}

    playId = parseInt(playId);
    window.open('/player/mp3player.php?' + reqString, 'mfMusicPlayer', 'width=750,height=625,scrollbars=0,resizable=0,status=0');
}


function openPopup(url, width, height, title, scroll) {
	var popupWidth	=	width ?		width	: 0;
	var popupHeight =	height ?	height	: 0;
	var title		=	title ?		title	: 'MusicFromNL';
    var scrollbar   =   scroll ? 1 : 0;    
    window.open( url, title, 'width=' + popupWidth + ',height=' + popupHeight + ' ,scrollbars=' + scrollbar + ',resizable=0,status=0' );
}

/**
 * Opent recommend.php met get argumenten.
 *
 *
 * @param  int	   sectionId		Id van de sectie van de pagina die verstuurd wordt.
 * @param  int     elementId		Id van het element dat verstuurd wordt. 
 * @param  string  url				URL naar de pagina
 * @param  bool    noSection		Als de pagina niet binnen een sectie valt, is er geen sectionId
 * @param  string  noSectionTitle	De titel van de pagina
 * @return void
 */
function openRecommend(sectionId, elementId, url, noSection, noSectionTitle)
{
	if (!noSection) {
		noSection = '';
	}
	if (!noSectionTitle) {
		noSectionTitle = '';
	}
    window.open('/shared/recommend.php?sectionId=' + sectionId + '&elementId=' + elementId + '&url=' + escape(url) + '&noSection=' + noSection + '&noSectionTitle=' + noSectionTitle , '', 'width=500,height=550,location=no,status=no,resizable=1,scrollbars=yes');
}


function hideFormElements(form, els)
{
    var el;

	for (var i = 0; i < els.length; i++) {
		var el = document.getElementById('fieldRow' + form + els[i]);
		if (el) {
            el.style.display = 'none';
		}
	}
}

function showFormElements(form, els)
{
		var el;

		for (var i = 0; i < els.length; i++) {
				var el = document.getElementById('fieldRow' + form + els[i]);
				if (el) {
						el.style.display = '';
				}
		}
}

function addEvent(obj, evType, fn, useCapture) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, useCapture);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    } else {
        // alert("Handler could not be attached");
    }
}


function mfReplaceMouseOvers() {
    els = document.getElementsByTagName('div');
    for (var i = 0; i < els.length; i++) {
        if (els[i].className == 'contentblock') {
            els[i].onmouseover = new Function("this.className = 'contentblock contentblock_hover';");
            els[i].onmouseout  = new Function("this.className = 'contentblock';");
        } else if (els[i].className == 'resultblock') {
            els[i].onmouseover = new Function("this.className = 'resultblock contentblock_hover';");
            els[i].onmouseout  = new Function("this.className = 'resultblock';");
        } else if (els[i].className == 'listblock') {
            els[i].onmouseover = new Function("this.className = 'listblock listblock_hover';");
            els[i].onmouseout  = new Function("this.className = 'listblock';");
        }
    }
}

function mfWriteEmail(name, domain) {
    if (!domain) {
        var domain = 'musicfrom.nl';
    }
    document.write('<a href="mail' + 'to:' + name + '@' + domain + '">' + name + '@' + domain + '</a>');
}

/*
function getFaqLinkArticle(text, article) {
    return "<a href=\"/faq/index.php?article=" + article + "\" onclick=\"window.open(this.href, '', 'width=750,height=500,scrollbars=1'); return false;\">" + text + "</a>";
}
*/
function getFaqLinkArticle(text, article) {
	if (isNaN(article)) {
		return "<a href=\"/faq/index.php?" + article + "\" onclick=\"window.open(this.href, '', 'width=750,height=500,scrollbars=1'); return false;\">" + text + "</a>";
	} else {
		return "<a href=\"/faq/index.php?article=" + article + "\" onclick=\"window.open(this.href, '', 'width=750,height=500,scrollbars=1'); return false;\">" + text + "</a>";
	}
}
function getFaqLinkCategory(text, category) {
    return "<a href=\"/faq/index.php?category=" + category + "\" onclick=\"window.open(this.href, '', 'width=750,height=500,scrollbars=1'); return false;\">" + text + "</a>";
}

function getFaqLink(text) {
    return "<a href=\"/faq/\" onclick=\"window.open(this.href, '', 'width=750,height=500,scrollbars=1'); return false;\">" + text + "</a>";
}

function clearSelectOptions(selectObject)
{
    if (selectObject && selectObject.options) {
        var tiltCount = 0;
        while (selectObject.options.length > 0) {
            if (tiltCount++ > 10000) {
                break;
            }
            selectObject.options[0] = null;
        }
    }
}


var srcs = new Array();
function replaceImgSrc(obj, src)
{
    srcs[obj] = obj.src;
    obj.src = src;
}

function restoreImgSrc(obj)
{
    if (srcs[obj]) {
        obj.src = srcs[obj];
    }
}

function getTopPx(obj) {
  var result = obj.offsetTop;
  while (obj.offsetParent) {
    obj = obj.offsetParent;
    result += obj.offsetTop;
  }
  return result;
}


function getLeftPx(obj) {
  var result = obj.offsetLeft;
  while (obj.offsetParent) {
    obj = obj.offsetParent;
    result += obj.offsetLeft;
  }
  return result;
}


function toggleDisplay(elementId)
{
	el = document.getElementById(elementId); 
	if (el.style.display == '') {
		el.style.display = 'none'; 
	} else {
		el.style.display = '';
	}
}

function toggleContent(contentId, targetId)
{
	var temp = document.getElementById(targetId).innerHTML;
	document.getElementById(targetId).innerHTML = document.getElementById(contentId).innerHTML;
	document.getElementById(contentId).innerHTML = temp;
}

addEvent(window, 'load', new Function('mfReplaceMouseOvers()'));

////////////////////////////////////////////////////////////   AJAX FUNCTIONALITEIT

function plopDiv (divId, args)
{
    if ($(divId) && args['url']) {
    
        new Ajax.Updater(divId, args['url'], { 
                    method      : 'post', 
                    parameters  : {
                        'parentUrl' : location.href,
                        'isAjax'    : true
                    }});
        //Effect.SlideDown(divId, { delay: 0, duration: 1 });
    }
    $(divId).style.display = '';

}

function plopDivClose(divId)
{
    $(divId).style.display = 'none';
}

function getRelated(divId, params)
{
    if ($(divId) && params) {
    
        new Ajax.Updater(divId, '/ajax/getrelated.php', { 
                    method      : 'post', 
                    parameters  : params});
    }
    $(divId).style.display = '';    

    closeOtherRelated(divId);
}

function closeOtherRelated(exceptDivId)
{
    var container;
    var className = 'relatedContent';

    var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
    var allElements = document.getElementsByTagName("*");

    var element;
    for (var i = 0; (element = allElements[i]) != null; i++) {
        var elementClass = element.className;
        if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)) {
            if (element.id != exceptDivId) {
                element.style.display = 'none';
            }
        }
    }
}


function getLoadingSign(type, sectionId, elementId, version) {

    var linkSpanId = 'linkSpan_' + type + '_' + sectionId + '_' + elementId + '_' + version;

    if ($(linkSpanId)) {
        new Ajax.Updater(linkSpanId, '/loadingsign.php', {
            parameters: { version   : version},
            requestHeaders: {'X-requestType' : 'Ajax'}
        });
    }
}


function getLinkButton(type, sectionId, elementId, version)
{    
    var linkSpanId = 'linkSpan_' + type + '_' + sectionId + '_' + elementId + '_' + version;
    returnUrl = location.href;

    if ($(linkSpanId)) {
        new Ajax.Updater(linkSpanId, '/linkbuttons.php', {
            parameters: {   type      : type,
                            sectionId : sectionId,
                            elementId : elementId,
                            returnUrl : returnUrl,
                            version   : version},
            requestHeaders: {'X-requestType' : 'Ajax'}
        });
    }
}

function getLinkCount(type, sectionId, elementId)
{
    var countSpanId = 'linkCountSpan_' + type + '_' + sectionId + '_' + elementId;
    if ($(countSpanId)) {
        new Ajax.Updater(countSpanId, '/linkCount.php', {
            parameters: {   sectionId : sectionId,
                            elementId : elementId,
                            type      : type}
        });
    }
}

function setLink(type, sectionId, elementId, version)
{    
    new Ajax.Request('/linkit.php', {
        method  : 'get',
        parameters: {   sectionId : sectionId,
                        elementId : elementId,
                        type      : type},
        onSuccess: function(transport) {
            getLinkButton(type, sectionId, elementId, version); 
        },
        requestHeaders: {'X-requestType' : 'Ajax'}
    });
}

function fillLinkSpans()
{
    var spans = window.document.getElementsByTagName("span");
    for (var i=0; i < spans.length; i++ ) {
        if(spans[i].id.substring(0,8) == "linkSpan" || spans[i].id.substring(0,13) == "linkCountSpan") {
            var ids = spans[i].id.split("_");
            var type = ids[1];
            var sectionId = ids[2];
            var elementId = ids[3];
            var version = ids[4];
            if (type == 'favorite' || type == 'tip' || type == 'artist' && (sectionId > 0 && elementId > 0)) {
                if (spans[i].id.substring(0,8) == "linkSpan") {
                    getLinkButton(type, sectionId, elementId, version);
                } else {
                    getLinkCount(type, sectionId, elementId, version);
                }
            }
        }
    }
}

function getRateButtons(sectionId, elementId)
{
    var rateSpanId = 'rateSpan_' + sectionId + '_' + elementId;
    returnUrl = location.href;
    new Ajax.Updater(rateSpanId, '/ratebuttons.php', {
        parameters: {   sectionId : sectionId,
                        elementId : elementId,
                        returnUrl : returnUrl},
        requestHeaders: {'X-requestType' : 'Ajax'}
    }); 
}

function setRating(rating, sectionId, elementId) {
    new Ajax.Request('/rateit.php', {
      method: 'get',
      parameters: { rating:     rating,
                    sectionId:  sectionId,
                    elementId:  elementId},
      onSuccess: function(transport) {getRateButtons(sectionId, elementId);},
      requestHeaders: {'X-requestType' : 'Ajax'}
      });
}

function fillSpans()
{
    var spans = window.document.getElementsByTagName("span");
    for (var i=0; i < spans.length; i++ ) {
        if(spans[i].id.substring(0,8) == "rateSpan") {
            var ids = spans[i].id.split("_");
            var sectionId = ids[1];
            var elementId = ids[2];
            if (sectionId > 0 && elementId > 0) {
                getRateButtons(sectionId, elementId);
            }
        }
    }
}


////////////////////////////////////////////////////////////   EXITLOG

/*

    2001-11-14:
        - also check parentElement (mv)

    2001-08-13:
        - bugfix: replace '#' in location.href with '%23' (mv)

*/

function replace(string,text,by) 
{
    if (string.length == 0 || text.length == 0)
        return string;

    var i = string.indexOf(text);
    if (((!i) && (text != string.substring(0,text.length))) || (i == -1))
        return string;

    var newstr = string.substring(0,i) + by;

    if (i + text.length < string.length)
        newstr += replace(string.substring(i + text.length, string.length), text, by);

    return newstr;
}

        
function doclick(e) 
{
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug

    if (targ.parentNode) var pe = targ.parentNode; else if (targ.parentElement) var pe = targ.parentElement;

    if (targ.tagName.toUpperCase() == 'IMG' && pe && pe.tagName.toUpperCase() == 'A') {
        targ = pe;
    }

    if (targ.tagName.toUpperCase() == 'A') {
        if (targ.href && targ.href.indexOf('http://') == 0 && targ.href.indexOf('musicfrom.') == -1) {
            targ.href = '/exitlog.php'
                + '?path=' + escape(replace(location.href, '#', '%23'))
                + '&url=' + escape(replace(targ.href, '#', '%23'));
            /*targ.href = '/exitlog.php'
                + '?path=' + escape(location.href)
                + '&url=' + escape(targ.href);*/
        }
    }
}


if (document.getElementById)
{
    document.onclick = doclick;
}
