var wptunes_HideTimes = 0;
var post_avg_votes = 0;
var post_ID;
var user_ID;
var wptunes_mode;

var pitchInstruments = new Array(
'Piano', 'Ocarina', 'Horn', 'Flute', 'Nylon Guitar', 'Steel Guitar', 'Saxophone', 'Trombone',
'Violin', 'Banjo', 'Bubbles', 'Xylophone', 'Sitar', 'Piccolo', 'Organ', 'Scream',
'Bagpipes', 'Harmonic', 'Accordion');
						
var instrumentCodes = new Array(
294, 267, 134, 166, 258, 402, 469, 452, 484, 43, 62, 493, 368, 229, 323, 348, 39, 183, 20);

var onLoadTimes = 0;
function DOMReady()
{
	if (onLoadTimes = null) onLoadTimes = 0;
	
	if(document.getElementById('wptune_items_view') == null && onLoadTimes < 2000)
	{
		onLoadTimes++;
		setTimeout('DOMReady();', 100);
	}
	else if (document.getElementById('wptune_items_view') != null)
	{
		hideSomeUiElements();
		fillNotesInfo();
		setSaveActions();
		if (typeof hideAdminUiElements == 'function')
			hideAdminUiElements();
	}
}

function initPostVars()
{
	var wptune_items_view = document.getElementById('wptune_items_view');
	if (wptune_items_view == null) return;
	post_avg_votes = getPostRate();
	post_ID = wptune_items_view.getAttribute('wptunes_post');
	user_ID = wptune_items_view.getAttribute('wptunes_user');
	wptunes_mode = wptune_items_view.getAttribute('wptunes_mode');
}

function hideSomeUiElements()
{
	var uielements = new Array ('postexcerpt', 'trackbacksdiv', 'commentstatusdiv', 'postcustom', 'notes-meta-boxes', 'advanced-sortables', 'sociable');
	var len = uielements.length;
	for (i=0; i<len; i++)
	{
		var uielement = document.getElementById(uielements[i]);
		if (uielement == null && wptunes_HideTimes < 2000)
		{
			wptunes_HideTimes++;
			setTimeout('hideSomeUiElements();', 20);
			return;
		}
	}
	for (i=0; i<len; i++)
	{
		var uielement = document.getElementById(uielements[i]);
		if (uielement == null)
		{
			continue;
		}
		var hiddenStyle = 'wptune_hidden';
		uielement.setAttribute('class', uielement.getAttribute('class') + ' ' + hiddenStyle);
	}
}
function setPostTitle(newTitle)
{
	document.getElementById('title').setAttribute('value', newTitle);
}
function setPostNotes(newNotes, replace)
{
	if (replace == true) clearAllNotes();
	loadNotes(newNotes);
}
function setPostRoot(newRoot)
{
	document.getElementById('list_roots').selectedIndex = parseInt(newRoot);
}
function setPostMode(newMode)
{
	document.getElementById('list_modes').selectedIndex = parseInt(newMode);
}
function setPostInstrument(newInstrument)
{
	var theInstrument = 0;
	var len = instrumentCodes.length;
	for (var i = 0; i < len; i++)
	{
		if (instrumentCodes[i] == parseInt(newInstrument))
		{
			theInstrument = i;
		}
	}
	document.getElementById('list_instruments').selectedIndex = theInstrument;
}
function setPostRate(newRate)
{
	if (newRate < 0) newRate = 0;
	if (newRate > 4) newRate = 4;
	
	var wptune_rate = document.getElementById('wptune_rate');
	
	if (wptune_rate == null) return 0;

	var ratePanel = wptune_rate.childNodes[1];
	if (ratePanel == null) ratePanel = wptune_rate.childNodes[0];
	
	var rows = ratePanel.rows;
	var row = rows[0];
	var cells = row.cells;
	var len = cells.length;
	for(var i = 0; i < len; i++)
	{
		var cell = cells[i];
		var elem = cell.childNodes[0];
		if (elem == null) continue;
		if (
		elem.getAttribute('id') != 'rate0' &&
		elem.getAttribute('id') != 'rate1' &&
		elem.getAttribute('id') != 'rate2' &&
		elem.getAttribute('id') != 'rate3' &&
		elem.getAttribute('id') != 'rate4') continue;
		
		var elemIndex = elem.getAttribute('id').substr(elem.getAttribute('id').length - 1, 1);
		
		if (elemIndex <= newRate)
		{
			elem.src = WpTunesPath + '/img/rate_selected.png';
			elem.setAttribute('state', 'on');
		}
		else
		{
			elem.src = WpTunesPath + '/img/rate_unselected.png';
			elem.setAttribute('state', 'off');
		}
	}
}
function setPostIsPitch(newBool)
{
	var show_pitch_editor = document.getElementById('show_pitch_editor');
	if (show_pitch_editor != null)
	{
		if (newBool == true || newBool == 1) show_pitch_editor.checked = true;
		else show_pitch_editor.checked = false;
	}
	
	showPitchEditor();
}

function getPostRoot()
{
	return document.getElementById('list_roots').selectedIndex;
}
function getPostMode()
{
	return document.getElementById('list_modes').selectedIndex;
}
function getPostInstrument()
{
	var theInstrument = document.getElementById('list_instruments').selectedIndex;
	return instrumentCodes[theInstrument];
}
function getPostRate()
{
	var newRate = 0;
	
	var wptune_rate = document.getElementById('wptune_rate');
	
	if (wptune_rate == null) return 0;

	var ratePanel = wptune_rate.childNodes[1];
	if (ratePanel == null) ratePanel = wptune_rate.childNodes[0];
	
	var rows = ratePanel.rows;
	var row = rows[0];
	var cells = row.cells;
	var len = cells.length;
	for(var i = 0; i < len; i++)
	{
		var cell = cells[i];
		var elem = cell.childNodes[0];
		if (elem == null) continue;
		if (
		elem.getAttribute('id') != 'rate0' &&
		elem.getAttribute('id') != 'rate1' &&
		elem.getAttribute('id') != 'rate2' &&
		elem.getAttribute('id') != 'rate3' &&
		elem.getAttribute('id') != 'rate4') continue;
		
		var elemIndex = elem.getAttribute('id').substr(elem.getAttribute('id').length - 1, 1);
		var elemState = (elem.getAttribute('state') == 'on');
		
		if (elemState) newRate = elemIndex;
	}
	
	return newRate;
}
function getPostIsPitch()
{
	var show_pitch_editor = document.getElementById('show_pitch_editor');
	if (show_pitch_editor == null) return '1';

	if (show_pitch_editor.checked) return '1';
	else return '0';
}

var setSaveActionsTimes = 0;
function setSaveActions()
{
	// auto-save tags on post save/publish
	if(document.getElementById('publish') == null && setSaveActionsTimes < 2000)
	{
    	setTimeout('setSaveActions();', 100);
    	setSaveActionsTimes++;
    }
    else if (document.getElementById('publish') != null)
    {
    	jQuery('#publish').click( notes_save_on_publish );
    	jQuery('#save-post').click( notes_save_on_publish );
    }
}
function notes_save_on_publish()
{
	document.getElementById('notes_value').setAttribute('value', getNotesString());
	document.getElementById('root_value').setAttribute('value', getPostRoot());
	document.getElementById('mode_value').setAttribute('value', getPostMode());
	document.getElementById('instrument_value').setAttribute('value', getPostInstrument());
	document.getElementById('ispitch_value').setAttribute('value', getPostIsPitch());
}
var fillNotesInfoTimes = 0;
function fillNotesInfo()
{
	if(document.getElementById('notes_value') == null && fillNotesInfoTimes < 2000)
	{
		fillNotesInfoTimes++;
		setTimeout('fillNotesInfo();', 100);
		
	}
	else if (document.getElementById('notes_value') != null)
	{
		initPostVars();
	
		if (document.getElementById('notes_value') == null) return;
		loadNotes(document.getElementById('notes_value').getAttribute('value'));
		setPostRoot(document.getElementById('root_value').getAttribute('value'));
		setPostMode(document.getElementById('mode_value').getAttribute('value'));
		setPostInstrument(document.getElementById('instrument_value').getAttribute('value'));
		setPostRate(post_avg_votes);
		setPostIsPitch(document.getElementById('ispitch_value').getAttribute('value'));
	}
}
function revertRate()
{
	setPostRate(post_avg_votes);
}


function addRating(newRate)
{
	var agree = confirm('Are you shure you want to vote?');
	if (!agree) return;
	var url = WpTunesPath + '/wptunes_pitch.php?action=rate&id=' + post_ID + '&rate=' + newRate + '&user=' + user_ID;
	state = 1;
	loadXMLDoc(url);
}

function _refreshRating()
{
	var url = WpTunesPath + '/wptunes_pitch.php?action=get_rating&id=' + post_ID + '&user=' + user_ID;
	state = 2;
	loadXMLDoc(url);
}
function refreshRating(xmlData)
{
	var averageRating,ratesCount,currentUserVotesCount;

	var dom, plist;
	
	if (typeof DOMParser != "undefined") {
        // Mozilla, Firefox, and related browsers
        dom = (new DOMParser()).parseFromString(xmlData, "application/xml");
    }
    else if (typeof ActiveXObject != "undefined") { 
        // Internet Explorer.
        try
        {
        var dom = XML.newDocument( );   // Create an empty document
        dom.loadXML(xmlData);              //  Parse text into it
        } catch (e) {
        	dom=new ActiveXObject("Microsoft.XMLDOM");
  			dom.async="false";
  			dom.loadXML(xmlData);
        }
    }
	
	if (dom == null)return false;
	
	plist = dom.lastChild;

	var dict;
	for (var i in plist.childNodes)
	{
		var aDict = plist.childNodes[i];
		if (aDict.nodeType == 1 && aDict.nodeName == 'dict')
		{
			dict = aDict;
			break;
		}
		continue;
	}
	
	var nodes = dict.childNodes;
	if (nodes == null || nodes.length == 0)return false;
	
	for (var i = 0; i < nodes.length; i++) {
		var param = nodes.item(i);
		if (param.nodeType != 1 || param.nodeName != 'key')
		{
			continue;
		}
		var paramName = param.lastChild.nodeValue;
		var nextNode;
		for (var j = i+1; j < nodes.length; j++) {
			var aNextNode = nodes.item(j);
			if (aNextNode.nodeType == 1 && (aNextNode.nodeName == 'string'))
			{
				nextNode = aNextNode;
				break;
			}
		}
		if (nextNode == null) return false;
		
		var paramValue = nextNode.lastChild.nodeValue;
		switch (paramName) {
			case 'averageRating':
				averageRating = paramValue;
				break;
			case 'ratesCount':
				ratesCount = paramValue;
				break;
			case 'currentUserVotesCount':
				currentUserVotesCount = paramValue;
				break;
		}
	}
	
	if (averageRating == null || averageRating == '') averageRating = '0';
	if (ratesCount == null || ratesCount == '') ratesCount = '0';
	
	var avgStr = 'Average rating ' + (parseInt(averageRating)+1) + ' stars from ' + ratesCount + ' votes.';
	if (ratesCount == '0') avgStr = 'No votes yet.';
	
	
	if (wptunes_mode == 'USER-POST')
	{
		if (user_ID != null && parseInt(user_ID) > 0)
		{
			if (parseInt(currentUserVotesCount) == 0)
			{
				avgStr += ' Please vote the pitch';
			}
			else
			{
				avgStr += ' You have already voted';
			}
		}
		else
		{
			avgStr += ' To vote you need to <a style="font-weight:bold;" href="/wp-login.php">Log in</a>';
		}
	}
	
	avgStr = '<nobr>' + avgStr + '</nobr>';
	
	document.getElementById('rate_text').innerHTML = avgStr;
	post_avg_votes = parseInt(averageRating);
	setPostRate(post_avg_votes);
	
	for (var i = 0; i < 5; i++)
	{
		document.getElementById('rate'+i).removeAttribute('onclick');
		document.getElementById('rate'+i).removeAttribute('onmouseover');
		document.getElementById('rate'+i).removeAttribute('onmouseout');
		document.getElementById('rate'+i).removeAttribute('style');
	}
}



// !XmlHttpRequest
var req;
var state = 0;
// 0 = doing nothing
// 1 = adding rate row
// 2 = getting rating info
 
function loadXMLDoc(url)
{
    req = null;
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
            try {
                req = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e){}
        }
    }
 
    if (req) {       
        req.open("GET", url, true);
        req.onreadystatechange = processReqChange;
        req.send(null);
    }
}
 
function processReqChange()
{
  try {
    // Just in complete state
    if (req.readyState == 4) {
        // for OK status
        if (req.status == 200) {
            // responce work around
            if(state == 1) // adding rate row
            {
	            if (req.responseText == 'OK')
	            {
    	        	_refreshRating();
    	        	return;
    	        }
    	        //alert(req.responseText);
            }
            else if (state == 2) // getting rating info
            {
            	var resp = req.responseText;
            	if (resp == null) resp = req.responseXML;
            	refreshRating(resp);
            }
        } else {
            // Error occured
        }
    }
  }
  catch( e ) {
      // alert('Caught Exception: ' + e.description);
      // Bugzilla Bug 238559 XMLHttpRequest needs a way to report networking errors
      // https://bugzilla.mozilla.org/show_bug.cgi?id=238559
  }
}

function showPitchEditor()
{
	var wptune_notes_container = document.getElementById('wptune_notes_container');
	if (wptune_notes_container == null) return;
	
	var show_pitch_editor, doShow;
	
	if (wptunes_mode == 'ADMIN-POST')
	{
		show_pitch_editor = document.getElementById('show_pitch_editor');
		if (show_pitch_editor != null) doShow = show_pitch_editor.checked;
		else doShow = true;
	}
	else
	{
		doShow = (document.getElementById('ispitch_value').getAttribute('value') == '1');
	}
	
	if (doShow == true)
	{
		wptune_notes_container.setAttribute('class', 'postbox')
	}
	else
	{
		wptune_notes_container.setAttribute('class', 'wptune_hidden')
	}
}

function showLoader(value)
{
	if (value == null)
		value = 0;
	var loaderPnl = document.getElementById('wptune_loader');
	var optionsPnl = document.getElementById('wptune_options');
	if (loaderPnl == null || optionsPnl == null)
		return;
	loaderPnl.setAttribute('class', 'wptune_tools');
	optionsPnl.setAttribute('class', 'wptune_hidden');
	for (var i = 0; i <= 16; i++)
	{
		var loaderImg = document.getElementById('loader_'+i);
		if (loaderImg == null)
			return;
		
		if (value >= i)
			loaderImg.setAttribute('src', WpTunesPath + '/img/loader.gif');
		else
			loaderImg.setAttribute('src', WpTunesPath + '/img/loader_empty.gif');
	}
	if (value == 16)
	{
		hideLoader();
	}
}
function hideLoader()
{
	var loaderPnl = document.getElementById('wptune_loader');
	var optionsPnl = document.getElementById('wptune_options');
	loaderPnl.setAttribute('class', 'wptune_hidden');
	optionsPnl.setAttribute('class', 'wptune_tools');
}