/* RANDOMS */

var msie = (((navigator.appVersion.indexOf("MSIE")!= -1)&&!window.opera) ? true : false);

/**
 * Blur every links when focused
 */
window.onload = function ()
{
	var links = document.getElementsByTagName("a");

	for (var i = 0; i < links.length; i++)
	{
		links[i].onfocus = function() { this.blur(); };
	}
};

/**
 * submit form
 */
function submitForm(formID)
{
	var form = document.getElementById(formID);
	
	if (form)
	{
		form.submit();
	}
}

/**
 * Display confirmation dialog and return results
 */
function confirmAction()
{
	return confirm("Vai tiešām vēlaties veikt šo darbību?");
}

/**
 * Insert contents (quick way) into an element
 *
 * @param string data - Data to insert into element
 * @param string dst_id - Destination element id
 */
function insertContents(data, dst_id)
{
	e = document.getElementById(dst_id);
	e.innerHTML = data;
}


/**
 * Changes elemets class to "sending"
 * Used in AJAX forms
 */
function setSending(id)
{
	var element = (document.getElementById ? document.getElementById(id) : null);

	if (!element) {return;}
	
	element.className = "sending";
}


/**
 * Changes elenets class to nothing
 * Used in AJAX forms
 */
function unsetSending(id)
{
	var element = (document.getElementById ? document.getElementById(id) : null);

	if (!element) {return;}
	
	element.className = "";
}

/**
 * Manages switching information tabs when viewing musicians profile
 */
function openTAB(id, url)
{
	//new Effect.Fade("container");

	var el_link = document.getElementById("a_"+id);
	var el_cont = document.getElementById(id+"_");

	// change link style
	
	var menu = document.getElementById("musician_info_menu");

	var els = menu.getElementsByTagName("a");

	for (var i=0; i<els.length; i++)
	{
		els[i].className = (els[i] == el_link ? "active" : "");
	}

	callajax('container', url);
	
	// change url

	document.location = "#" + id;
	
	return false;
}


/**
* Call ajax updater
*
* @param string div_id Id of the DIV where to put returned information
* @param string url Address to call
* @param boolean silent Should we show loading bar
*/
function callajax(div_id, url, silent)
{
	if (div_id == "")
	{
		new Ajax.Request(url, {
			asynchronous:true
		});
	}
	else
	{
		new Ajax.Updater(div_id, url, {
	
			asynchronous:true, 
			evalScripts:true,
	
			onCreate: function() {
				if (!silent)
				{
					var div = $(div_id);
					div.update('').addClassName('loading');
				}
			},
	
			onSuccess: function(transport){
				if (!silent)
				{
					var div = $(div_id);
					div.removeClassName('loading');
				}
			}    
			
		});
	}
}


/**
 * musicController object controlls music
 * 
 * @requires prototype.js
 * 
 */
var musicController = {
	
	/** store the code of currently playing song here */
	currentlyPlaying: '',

	/** tsore top 1 song. this will be played, if nothing is loaded */
	top1Song: '',


	/**
	 * Sends a request to flash player to play or stop playing a song
	 * 
	 * @param string val code of the song
	 */
    play: function(code){
		if(this.currentlyPlaying != code) {
			if(this.currentlyPlaying.length > 1) {
				this.markStopped(this.currentlyPlaying);
			}
			this.markPlaying(code);
			$('randomflashplayer').playMusic(code);	
    	}
    	else {
			this.markStopped(this.currentlyPlaying);
			this.pause();
			this.currentlyPlaying = "";
    	}
    },
    
    /**
     * Stop the currently playing song
     */
    pause: function(){
    	$('randomflashplayer').stopMusic(this.currentlyPlaying);
    },
    
    /**
     * Marks currently playing song as active by adding 'active' class
     * Also finds previous songs marked as playing and marks them as stopped
     * 
     * @param string val code of the song
     */
    markPlaying: function(code) {

		this.currentlyPlaying = code;
		
		var anchors = $A(document.getElementsByTagName('a'));

		if(!code) {
			currentId = this.currentlyPlaying;
		}
		else {
			currentId = code;
		}
		

		// loop through all anchor tags. prototype Enumerables metodes uz IE gļuko!! :(
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];

			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.match(currentId))){
						
				$(anchor).addClassName('active');
				$(anchor).ancestors().find(function(el){
					if(el.className.match('song_')) {
						el.addClassName('active');
					}
				})
			}
		}
	
		callajax("", webroot+"music/count/"+currentId);
    },


	/**
	 * Marks this song stopped by removing 'active' class
	 * 
	 * @param string val code of the currently playing song
	 */
    markStopped: function(code) {
		var anchors = $A(document.getElementsByTagName('a'));


		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.match(code))){
				$(anchor).removeClassName('active');
				$(anchor).ancestors().find(function(el){
					if(el.className.match('song_')) {
						el.removeClassName('active');
					}
				})
				
			}
		}
		
	
		this.currentlyPlaying = '';
		    	
    },
    
    /**
     * Check if next song exists and return it
     * 
     * @return
     */
    checkForNext: function(currentId) {
    	
    		var nextsong = false;
			var anchors = $A(document.getElementsByTagName('a'));
			var getnextid = 0;
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				var relAttribute = String(anchor.getAttribute('rel'));
				
				if (anchor.getAttribute('href') && (relAttribute.length>5)){
					if(getnextid == 1) {
						getnextid = 0;
						nextsong = relAttribute;
					}
					if(relAttribute.match(currentId)) {
						getnextid = 1;
						
					}
					
				}
			}
			return nextsong;
    	
    },
    
    /**
     * Check if previous song exists and return it
     * 
     * @return
     */
    checkForPrev: function(currentId) {
    		var prevsong = false;
    		var maybeprevsong = false;
			var anchors = $A(document.getElementsByTagName('a'));
			var getnextid = 0;
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				var relAttribute = String(anchor.getAttribute('rel'));
				
				if (anchor.getAttribute('href') && (relAttribute.length>5)){
					if(relAttribute.match(currentId)) {
						if(maybeprevsong) {
							prevsong = maybeprevsong;
						}
					}
					if(!prevsong) {
						maybeprevsong = relAttribute;
					}
				}
			}
			return prevsong;
    },
    
    
    /**
     * Check if next song should be played automatically
     */
    checkForAutoplay: function() {
       	if($('playallsongs') && $('playallsongs').checked) {
    		return true;
    	}
    	else {
			return false;
    	}
    },
    
    
    
    /**
     * Sets a song (code) as Top1
     * 
     * @param string songId - ID/code/filename for the song to mark Top 1
     */
    setTop1Song: function(songId) {
    	if(songId) {
    		this.top1Song = songId;
    	}	
    },
    

	/**
	 * Returns Top1 song
	 */
    getTop1Song: function() {
		if(this.top1Song) {
			return this.top1Song;
		}
		else {
			return false;
		}
    },
    
    /**
     * pop up a separate window with current song
     */
    popupPlayer: function(code) {
    	if(!code){
    		if(this.checkForAutoplay()) {
    			code = this.getTop1Song();
    		}
    	}
    	newplayer = window.open(webroot+'music/standalone/'+code,'randoms_player',"left=150,top=100,width=450,height=50,status=no,resizable=no");
    	newplayer.focus();
    }
};

/* Multiple file selector (for uploading files) */
function MultiSelector( list_target, max ){this.list_target = list_target;this.count = 0;this.id = 0;if( max ){this.max = max;} else {this.max = -1;};this.addElement = function( element ){if( element.tagName == 'INPUT' && element.type == 'file' ){element.name = 'file_' + this.id++;element.multi_selector = this;element.onchange = function(){var new_element = document.createElement( 'input' );new_element.type = 'file';this.parentNode.insertBefore( new_element, this );this.multi_selector.addElement( new_element );this.multi_selector.addListRow( this );this.style.position = 'absolute';this.style.left = '-1000px';};if( this.max != -1 && this.count >= this.max ){element.disabled = true;};this.count++;this.current_element = element;} else {alert( 'Error: not a file input element' );};};this.addListRow = function( element ){var new_row = document.createElement( 'div' );var new_row_button = document.createElement( 'input' );new_row_button.type = 'button';new_row_button.value = 'dzēst';new_row.element = element;new_row_button.onclick= function(){this.parentNode.element.parentNode.removeChild( this.parentNode.element );this.parentNode.parentNode.removeChild( this.parentNode );this.parentNode.element.multi_selector.count--;this.parentNode.element.multi_selector.current_element.disabled = false;return false;};new_row.innerHTML = element.value;new_row.appendChild( new_row_button );this.list_target.appendChild( new_row );};};

/**
 * Print email link (protection from spambots)
 * If javascript is disabled, nothing is visible
 * 
 * @param string p1 Part 1 - this is username
 * @param string p2 Part 2 - this is domain
 * @param string p3 Part 3 - this is TLD
 */

function writemail(p1, p2, p3)
{
	document.write("<a href='mailto:"+p1+"@"+p2+"."+p3+"'>"+p1+"@"+p2+"."+p3+"</a>");
}


 /**
 *
 *
 */
function includeCSS(stylesheet)
{
	var old_css = document.getElementById("cstyle");
	
	if (old_css)
	{
		document.getElementsByTagName("head")[0].removeChild(old_css);
	}

	var css = document.createElement("link");

	css.rel = "stylesheet";
	css.type = "text/css";
	css.id = "cstyle";
	css.href = webroot+"css/"+stylesheet+".css";
	
	document.getElementsByTagName("head")[0].appendChild(css);

	var today = new Date();
	var expire = new Date();

	expire.setTime(today.getTime() + 30 * 1000 * 60 * 60 * 24); //1month
	
	document.cookie = "stylesheet="+stylesheet+"; path=/; expires="+expire.toGMTString();
}

/**
 * Add new row to select element
 * @param select_id number Id of select box
 * @param value text New element's value
 * @param content text New element's text
 */
function appendToSelect(select_id, value, content)
{
	var sel = document.getElementById(select_id);
	
	if (sel)
	{
		var opt = document.createElement("option");
		
		var txt = document.createTextNode(content);
		
		opt.value = value;
	
		opt.appendChild(txt);
			
		sel.appendChild(opt);
	}
}


/**
 * Empty select element
 * @param select_id number Id of select box to be cleared
 */
function clearSelect(select_id)
{
	var sel = document.getElementById(select_id);

	if (sel)
	{
		var len = sel.length;
		
		for (var i=len-1; i>-1; i--)
		{
			sel.remove(i);
		}
	}
}

/**
 * Update "Chars left" field when writing forum post and strip
 * message if its too long
 *
 * @param el textarea element
 */
function updatePostLength(el)
{
	if (el.value.length > 2500)
	{
		el.value = el.value.substr(0, 2500)
	}
	
	$("chrleft").update(2500 - el.value.length);
}

/**
 *
 *
 *
 * @param el textarea element
 */
function checkPostText(el)
{
	if (el.value == "Tavs komentārs...")
	{
		el.value = "";
		
		el.style.color = "#000";
	}
}


/**
 * Reply to forum post
 *
 * @param id number Post ID to reply to
 */
function reply(id)
{
	if ($("PostReplyId").value == id)
	{
		$("quoteline").update();
	
		$("PostReplyId").value = 0;
	}
	else
	{
		$("quoteline").update($("quoteline"+id).innerHTML);
	
		$("PostReplyId").value = id;
	}
}

/**
 * Get element's X position (top left corner)
 *
 * @param string el Element Id
 * @return int
 */
function getX(el)
{
	var curleft = 0;

	if (el.offsetParent)
	{
		while (el.offsetParent)	
		{
			curleft += el.offsetLeft;
			el = el.offsetParent;
		}
	}
	else if (el.x)
	{
		curleft += el.x;
	}
	
	return curleft;
}

/**
 * Get element's Y position (top left corner)
 *
 * @param string el Element Id
 * @return int
 */
function getY(el)
{
	var curtop = 0;
	
	if (el.offsetParent)
	{
		while (el.offsetParent)
		{
			curtop += el.offsetTop;
			el = el.offsetParent;
		}
	}
	else if (el.y)
	{
		curtop += el.y;
	}
	
	return curtop;
}