//	============================================================================
//	muzic_toolbox.js
//	
//	ericb@muzic.com		1/3/08
//	copyright 2008 - 2010 muzic.com
//

var gSiteRoot = gMuzicRoot;

// stop href to a target=_blank from triggering js on enclosing div
// varies depending
function preventBubble(e){
	if (e && e.stopPropagation) //if stopPropagation method supported
		e.stopPropagation()
	else
		event.cancelBubble=true
}

//function checks to see if the player frame is already loaded.
//if so, it will load the specified frames as specified in the player/target variables
//if not, it will load the frame, passing along the target and player information in the querystring
function openPlayerFrame(player,event,target) {
	// prevent click from reaching an underlying song row's onclick
	Event.stop(event);

	//make sure that both variables are defined, in case they were not passed into the call
	if (target === undefined) { var target = ""; }
	if (player === undefined) { var player = ""; }
	
	//if the target was empty, set it to the current page URL
	if (target == "") { target = self.location.href; }
	
	//we want to make the value safe, so encode the "&" with "||" before setting the location
	//this helps us parse out the querystring in the frameset
	target = target.replace(new RegExp("&", "g"), "||");

	//set the top location and return false
//	top.location = gMuzicRoot + "frames.php?target=" + target + "&" + player; // std frames version
	window.frames['player_frame'].location = gMuzicRoot + "muzicplayer/player.php?target=" + target + "&" + player; // iframe version
	$('apDiv1').style.display = 'block';
	
	return false;
}

//function to show/hide the search bar
function toggleSearch() {
	var elem, field;
	if( document.getElementById ) { elem = document.getElementById("admin_searchbar"); } 
	else if( document.all ) { elem = document.all["admin_searchbar"]; } 
	else if( document.layers ) { elem = document.layers["admin_searchbar"]; }
	if (elem.style.display != "block") { 
		elem.style.display = "block"; 
		field = document.getElementById("search_name");
		field.focus();
	} else { elem.style.display = "none"; }
	return false;
}

//function to fix the suckerfish menu hover problem in IE6
//menus are from http://www.htmldog.com/articles/suckerfish/dropdowns/
//this should only do work on pages that have the menu when the user is on IE6
function sfHover() {
	var ie6 = (navigator.appVersion.indexOf("MSIE 6.0") > -1);
	var hasMenu = (document.getElementById("nav"));
	
	if (ie6 && hasMenu) {
		var sfEls = document.getElementById("nav").getElementsByTagName("LI");
		if (sfEls) {
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() { this.className+=" sfhover"; }         
				sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); }
			}
		}
	}
}

// enable lightbox login after page has loaded (link breaks if not)
Event.observe(window, "load", function() {
	// if not logged in (login link present on page)
	var modal_link = $('login-modal');
	//console.log(modal_link);
	if(modal_link != null){
		// hide static login url
		$('login-static').remove();
		// show lightbox url
		modal_link.style.display = 'inline';
	}
});

// load index page's muzic intel panel
Event.observe(window, "load", function(){
	if( $('intel_box') != undefined ){
		new Ajax.Request( gMuzicRoot + 'views/artistcloud.php',
		{
			method: 'get',
			onSuccess: function( transport ) {
				// add tab ?
				$('tab-1').innerHTML = transport.responseText;
				new Ajax.Request( gMuzicRoot + 'views/topSongs.php',
				{
					method: 'get',
					onSuccess: function( transport ) {
						// add tab ?
						$('tab-2').innerHTML = transport.responseText;
						new Ajax.Request( gMuzicRoot + 'views/frontpageblogs.php',
						{
							method: 'get',
							onSuccess: function( transport ) {
								// add tab ?
								$('tab-3').innerHTML = transport.responseText;
							}
						} );
					}
				} );
			}
		} );	
	}
} );


// lightbox login processing
function login_modal() {
  new Ajax.Request( gMuzicRoot + 'login-process.php',
  {
    method: 'post',
    postBody: $('loginform').serialize(),
    onSuccess: function( transport ) {
      if( transport.responseText.match( /\<ok\/\>/ ) ){
		//$('links').innerHTML = transport.responseText;
		//Modalbox.hide();	// ugly effect, at least in my current testing
		window.location.reload();
      } else {
		//console.log(transport.responseText);
		$('login_error').innerHTML = transport.responseText;
        $('login_error').style.display='block';
	  }
    }
  } );
}

function showSongRows(hrefElem)
{
	var metaRowElem = $(hrefElem).up('div').up('div');
	var hiddenRows = metaRowElem.select('div.more_song-hidden');
//	console.log(hiddenRows);
	hiddenRows.each( function(row) {
			row.removeClassName('more_song-hidden');			
			row.addClassName('more_song');
			Effect.SlideDown((row), {duration: 0.5});
// 			row.style.display='block';
		}
	);
}

// used to pop open the original artist pic from their profile pic
function openPic(url,winName,winParams)	
{
	var theWindow = window.open(url,winName,winParams);
	if (theWindow)	{
		theWindow.focus();
	}
}


function recordBlogClick(elem)
{
	var url = gSiteRoot + 'proc/blogclick/' + $(elem).id;
	new Ajax.Request( url,
	{
		method: 'get',
		onSuccess: function( transport ) {
			//console.log(transport.responseText);
		}
	} );
	
	preventBubble(elem);
}

// from javascript: the definitive  guide
/**
 * Add a rollover effect to the specified image, by adding event
 * handlers to switch the image to the specified URL while the
 * mouse is over the image.
 *
 * If the image is specified as a string, search for an image with that
 * string as its id or name attribute.
 * 
 * This method sets the onmouseover and onmouseout event handler properties
 * of the specified image, overwriting and discarding any handlers previously
 * set on those properties.
 */
function addRollover(img, rolloverURL) {
    if (typeof img == "string") {  // If img is a string,
        var id = img;              // it is an id, not an image
        img = null;                // and we don't have an image yet.

        // First try looking the image up by id
        if (document.getElementById) img = document.getElementById(id);
        else if (document.all) img = document.all[id];

        // If not found by id, try looking the image up by name.
        if (!img) img = document.images[id];
        
        // If we couldn't find the image, do nothing and fail silently
        if (!img) return;
    }

    // If we found an element but it is not an <img> tag, we also fail
    if (img.tagName.toLowerCase() != "img") return;

    // Remember the original URL of the image
    var baseURL = img.src;

    // Preload the rollover image into the browser's cache
    (new Image()).src = rolloverURL;

    img.onmouseover = function() { img.src = rolloverURL; }
    img.onmouseout = function() { img.src = baseURL; }
}

/**
 * Find all <img> tags in the document that have a "rollover"
 * attribute on them.  Use the value of this attribute as the URL of an 
 * image to be displayed when the mouse passes over the image and set 
 * appropriate event handlers to create the rollover effect.
 */
function initRollovers() {
    var images = document.getElementsByTagName("img");
    for(var i = 0; i < images.length; i++) {
        var image = images[i];
        var rolloverURL = image.getAttribute("rollover");
        if (rolloverURL) addRollover(image, rolloverURL);
    }
}


// NEW STUFF, using Prototype.js
// eb - 7/3/08

function removePlaylistItem(playlist_id, item_id, elem_id)
{
	var params = $H();
	params.set("pl_id",playlist_id);
	params.set("id",item_id);
	//console.log( params.toQueryString() );
	new Ajax.Request("remove_pl_item.php", {
		method: "post",
		parameters: { data: params.toQueryString() },
		onSuccess: function(transport){ 
			//console.log(transport.responseJSON.deleted);
			//var elem_id = "item_" + item_id;
			if('deleted' in transport.responseJSON ){
				// next two lines are useful if removing an item from a user's list of their own playlists, but not the general purpose
					Effect.Fade(elem_id);
					$(elem_id).remove();
				// change the button and javascript to become "addPlaylistItem"
				var fave_elem = $(elem_id);
				var img_elem = fave_elem.select('img');
			}
		},
		onFailure: function(){ alert("Something went wrong...") }
	});
}

function toggleFaveListBtn(event, elem, playlist_id, item_id, item_type)
{
	Event.stop(event);

	var url;
	if( elem.className.endsWith('add') )
		url = gMuzicRoot+"add_fave_item.php";
	else
		url = gMuzicRoot+"remove_fave_item.php";
	
	var currClass = elem.className;
	$(elem).removeClassName(currClass);
	$(elem).addClassName('list_btn-busy');

	var params = $H();
	params.set("pl_id",playlist_id);
	params.set("id",item_id);
	params.set("type",item_type);
	
	new Ajax.Request(url, {
		method: "post",
		parameters: { data: params.toQueryString() },
		onSuccess: function(transport){ 
			$(elem).removeClassName('list_btn-busy');
			if('removed' in transport.responseJSON )
				$(elem).addClassName('list_btn-fave_add');
			else
				$(elem).addClassName('list_btn-fave_remove');
		},
		onException: function(req,exception) {
			//alert("The request had a fatal exception thrown.\n\n" + exception.message + "\n");
			console.log("The request had a fatal exception thrown.\n\n" + exception.message + "\n");
			console.log(exception.description + "\n");
			console.log("isSameOrigin: " + req.isSameOrigin() + "\n");
			console.log("url: " + req.url + "\n");
			return true;
		},
		onFailure: function(){ alert("Something went wrong...") }
	});
}

function removeFaveThumb(event, elem, item_id, item_type)
{
	Event.stop(event);

	var url = gMuzicRoot+"remove_fave_item.php";
	
	var currClass = elem.className;
	$(elem).removeClassName(currClass);
	$(elem).addClassName('thumb-busy');

	var params = $H();
	params.set("pl_id",null);
	params.set("id",item_id);
	params.set("type",item_type);
	
	new Ajax.Request(url, {
		method: "post",
		parameters: { data: params.toQueryString() },
		onSuccess: function(transport){ 
			$(elem).parentNode.remove();
			$('fave_count').innerHTML = transport.responseJSON.count;
			//console.log(transport.responseJSON);
		},
		onException: function(req,exception) {
			alert("The request had a fatal exception thrown.\n\n" + exception.message + "\n");
			return true;
		},
		onFailure: function(){ alert("Something went wrong...") }
	});
}

// Toggles a tab in our "Tabbed Box" content objects
function showTab(elem,name)
{
	// find the tab set to #current and remove that id
	$('current').id = '';
	
	// find the previous content body set to .content_tab-visible & set that to hidden
	var visible_tab_bodies = $$('.content_tab-visible');
	var visible_tab_body = visible_tab_bodies[0];
	visible_tab_body.removeClassName('content_tab-visible');
	visible_tab_body.addClassName('content_tab-hidden');
	
	// set this element's id to #current
	elem.id = 'current';
		
	// find this tab's content body, and set it to .content_tab-visible
	$(name).removeClassName('content_tab-hidden');
	$(name).addClassName('content_tab-visible');
}



function toggleCheckBoxes(formName) {
	// toggle Check Boxes using Prototype Library
	var form=$(formName);
	var i=form.getElements('checkbox');
	i.each( function(item) {
		if (item.checked)
			item.checked=false
		else
			item.checked=true
	}
	);
}

/*-----------------------------------------------------------
    Toggles element's display value
    Input: any number of element id's
    Output: none 
    ---------------------------------------------------------*/
function toggleDisp() {
    for (var i=0;i<arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}
/*-----------------------------------------------------------
    Toggles tabs - Closes any open tabs, and then opens current tab
    Input:     1.The number of the current tab
                    2.The number of tabs
                    3.(optional)The number of the tab to leave open
    Output: none 
    ---------------------------------------------------------*/
function toggleTab(num,numelems,opennum) {
    if ($('tabContent'+num).style.display == 'none'){
        for (var i=1;i<=numelems;i++){
            if ((opennum == null) || (opennum != i)){
                var temph = 'tabHeader'+i;
                var h = $(temph);
                if (!h){
                    var h = $('tabHeaderActive');
                    h.id = temph;
                }
                var tempc = 'tabContent'+i;
                var c = $(tempc);
                if(c.style.display != 'none'){
                    toggleDisp(tempc);
                }
            }
        }
        var h = $('tabHeader'+num);
        if (h)
            h.id = 'tabHeaderActive';
        h.blur();
        var c = $('tabContent'+num);
      //  c.style.marginTop = '2px';
        toggleDisp('tabContent'+num);
    }
}


function startIngest(blog_id)
{
	// throw up a confirmation dialog
	if(confirm("Really? You sure you want to run the ingester now? This will lock your session until it's done. It's better to just put it in the queue.")){
		// ajax call to ingester_gears.php?blog_id=blog_id
		new Ajax.Request( 'ingester_gears.php?blog_id=' + blog_id,
		{
		method: 'post',
		onSuccess: function( transport ) {
				if( transport.responseText.match( /\<ok\/\>/ ) ){
					//$('links').innerHTML = transport.responseText;
					window.location.reload();
				} else {
					console.log(transport.responseText);
					//$('login_error').innerHTML = transport.responseText;
					//$('login_error').style.display='block';
				}
			}
		} );
		$('ingest_link').style.display='none';
	}
}
