/*
	- optionally log in first
	- get username and password from php call that check ref domain
	- log in doesn't seem to be working anymore
	
	- get categories possibly from /wp-admin/sidebar.php
	- set category/ies properly
	
	- stylesheet
	- internationalised
	- widgetised
	
	
*/

//			var cats = new Array()

			var http_request = false;
		   	target = 'qp_target'
	
		   	username = "username"
		   	password = "password"
	
		   	responseCode = new Array('uninitialized','loading','loaded','interactive','complete')

//	post_data = new Array('action','post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status');
		   	post_data = new Array('action','mode','publish','content','post_title','user_ID','post_category');

		   	action = "post"
		   	post_author = 10	//	1 is admin
		   	user_ID = post_author
		 //  	post_category[0] = 3	//	1 is uncategorised
		 	var new_category
		 	allow_new = false
		 	refresh = true
//		 	refresh = false
		   	post_status = "publish"
		   	publish = post_status
		   	mode = 'sidebar'
		   	var post_title

		   	var _wpnonce



   function makePOSTRequest(url, parameters, returnMethod) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         setNode(target,'Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = eval(returnMethod);
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }


	function _loginResponse() {
		reportState(http_request.readyState)
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				result = http_request.responseText;
				if ( ! result.indexOf('logout') ) {
					
//					alert(result)
					setNode(target, "login failed")
					return
				} else {
//					setError('i')
					_post()
				}
			} else {
				setNode(target,'There was a problem with the request.\n');
				setError('_loginResponse ' + http_request.status)
			}
		}
	}
   
   
	function _logoutResponse() {
		reportState(http_request.readyState)
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				result = http_request.responseText;
//				alert(result)
//				if ( ! result.indexOf("Successfully logged you out") ) {
				if ( result.indexOf("Successfully logged you out") ) {
					setOK('Logged out')
					if ( refresh )
						location.href = location.href
//					alert('logged out')
				} else {
					setError('Log out failed ' + result)
				}
			} else {
				setNode(target,'There was a problem with the request.\n');
				setError('_logoutResponse ' + http_request.status)
			}
		}
	}
   
  
	function _requestLogin() {
//   test-ajax-login.php?a=b
		var poststr = "a=b"
		makePOSTRequest('quickpost/quickpost.php', poststr, '_requestLoginResponse');
	}


	function _requestLoginResponse() {
		reportState(http_request.readyState)
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				result = http_request.responseText;
//				alert(result)
				username = result.substring(result.indexOf('u=')+2, result.indexOf('&p='))
//				alert(username)
				password = result.substring(result.indexOf('&p=')+3, result.length)
//				alert(password)
				_login()
			} else {
				setNode(target,'There was a problem with the request.\n');
				setError('_requestLoginResponse ' + http_request.status)
			}
		}
	}  

   
	function _login() {
//		alert('login')
		var poststr = "log=" + username + "&pwd=" + password
		makePOSTRequest('wp-login.php', poststr, '_loginResponse');
	}
	
	
	function _logout() {
		var poststr = "action=logout"
		makePOSTRequest('wp-login.php', poststr, '_logoutResponse');
	}
	
	
	function _formPrepare() {

		node = document.getElementById(target)
		
//				<form action="javascript:_login()">
		form = document.createElement('form')
		form.setAttribute('action', "javascript:main()")
		form.setAttribute('name', 'qp_form')

		title_label = document.createElement('label')
		title_label.setAttribute('for','post_title')
		txt = document.createTextNode('Title')
		title_label.appendChild(txt)
//				<input type='text' name="post_title" id="post_title" value="" />
		title = document.createElement('input')
		title.setAttribute('type', 'text')
		title.setAttribute('name', 'post_title')
		title.setAttribute('id', 'post_title')
		title.setAttribute('value', '')
		
		br = document.createElement('br')
		br2 = document.createElement('br')
		br3 = document.createElement('br')
		br4 = document.createElement('br')
		br5 = document.createElement('br')
		
//				<textarea name="post_content" id="post_content">
//		debug('textarea')
		the_content = document.createElement('textarea')
//		debug('textarea')
		the_content.setAttribute('id', 'post_content')
		the_content.setAttribute('name', 'content')
		

		cat_label = document.createElement('label')
		cat_label.setAttribute('for','category')
		txt = document.createTextNode('Category')
		cat_label.appendChild(txt)
		
		categories = document.createElement('select')
		categories.setAttribute('id', 'post_category')
		categories.setAttribute('name', 'post_category')
		categories.setAttribute('onChange', "categoryChange(document.qp_form.post_category)")

		opt = document.createElement('option')
		txt = document.createTextNode('Select a ...')
		opt.setAttribute('value', '')
		opt.appendChild(txt)
		categories.appendChild(opt)

		if ( allow_new ) {
			opt = document.createElement('option')
			txt = document.createTextNode('New ...')
			opt.setAttribute('value', '')
			opt.appendChild(txt)
			categories.appendChild(opt)
		}
		
		for ( i = 0; i < cats.length; i++ ) {
			if ( ! cats[i] ) 
				continue
			
			cat_ID = cats[i].substring(0, cats[i].indexOf("="))
			cat_name = cats[i].substring(cats[i].indexOf("=")+1, cats[i].length)
			
			
			if ( cat_name.toLowerCase().indexOf("uncateg") == 0 )
				continue
			opt = document.createElement('option')
			opt.setAttribute('value', cat_ID)
			txt = document.createTextNode(cat_name)
			opt.appendChild(txt)
			categories.appendChild(opt)
		}
	
	
		if ( allow_new ) {
			catnew_label = document.createElement('label')
			catnew_label.setAttribute('for','catnew')
			txt = document.createTextNode('New Category')
			catnew_label.appendChild(txt)
//				<input type='text' name="post_catnew" id="post_catnew" value="" />
			catnew = document.createElement('input')
			catnew.setAttribute('type', 'text')
			catnew.setAttribute('name', 'catnew')
			catnew.setAttribute('id', 'catnew')
			catnew.setAttribute('value', '')
			catnew.setAttribute('onChange', "categoryChange(document.qp_form.catnew)")
		}

//				<input type="button" name="button" value="Submit" onclick="javascript:_post();">
//				<input type="submit" name="button" value="Normal Submit Button">
		submit = document.createElement('input')
		submit.setAttribute('type', 'submit')
		submit.setAttribute('value', 'Send Breath')
		

		form.appendChild(title)
		form.appendChild(title_label)
		form.appendChild(br)
		form.appendChild(the_content)
		form.appendChild(br2)
		form.appendChild(categories)
		form.appendChild(cat_label)
		form.appendChild(br3)
		if ( allow_new ) {
			form.appendChild(catnew)
			form.appendChild(catnew_label)
			form.appendChild(br4)
		}
		form.appendChild(br5)
		form.appendChild(submit)
		
		node.appendChild(form)
	}
	
	
	function _post () {

		post_title = document.getElementById("post_title").value
		the_content = document.getElementById("post_content").value
				
		if ( allow_new && document.getElementById("catnew").value != "" ) {
			post_category = document.getElementById("catnew").value
//			new_category = post_category
			createNewCategory(post_category)
			return
		}
		else
			post_category = document.getElementById("post_category").options[document.getElementById("post_category").selectedIndex].value
			
//		alert(post_category)
		
		var poststr = ""
		for ( i = 0; i < post_data.length; i++ ) {
			val = eval(post_data[i])
	//		alert(val)
			poststr += post_data[i] + "=" + encodeURI(val) + "&";
		}
		poststr += "post_category[0]=" + encodeURI(post_category) + "&";
		poststr += "content=" + encodeURI(the_content) + "&";

//		alert(poststr)
		makePOSTRequest('wp-admin/post.php', poststr, '_postResponse');
	}
	
	
	function _postResponse() {
		reportState(http_request.readyState)
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				result = http_request.responseText;
//	alert(result)
//	test for a successful post
				if ( result.indexOf("WordPress &#8250; Posted") > 1 ) {
					setNode(target, "Thanks for your breath<br /><em>" + post_title + "</em>")
					_logout()
					return
				} else {

//	see if we have been returned a wpnonce id for posting
					var expr 
					if ( ! document.all ) {
						var expr = "\'_wpnonce\'\ +value=\'(.+)\'";
						re = new RegExp(expr, "gim")
					} else {
						expr =  /\'_wpnonce\'\s+value=\'(.+)\'/;
		//				alert(expr)
						re = new RegExp(expr)
					}
					match = re.exec(result)

					if ( ! match || match.length == 0 ) {
						setNode(target, 'There was a problem with the request.\n');
						setError('_postResponse no match')
						_logout()
						return
	//					alert( match.length )
//						alert( result )
					} else {
						post_data.push("_wpnonce")
						_wpnonce = match[1]
//						debug("wpnonce " + _wpnonce)
						_post()
					}
				} 			
			} else {
				setNode(target,'There was a problem with the request.\n');
				setError('_postResponse ' + http_request.status)
				_logout()
				return
			}
		}
	}
	
	
	function categoryChange(that) {
//		alert(that.name)
		if ( that.name == "post_category" ) {
			if ( that.selectedIndex > 1 && allow_new)
				that.form.catnew.value = ""
			else if ( that.selectedIndex == 1 && allow_new)
				that.form.catnew.focus()
		} else {
			that.form.post_category.selectedIndex = 1
		}
	}
	

	function createNewCategory (category) {
//		alert("New Category " + category)
		var poststr = ""
		poststr += "action=" + encodeURI("addcat")
		poststr += "&cat_name=" + encodeURI(category)
		if ( _wpnonce )
			poststr += "&_wpnonce=" + encodeURI(_wpnonce)		
//		alert(poststr)
		makePOSTRequest('wp-admin/categories.php', poststr, '_addCatResponse');
		
	}
	
	
	function _addCatResponse() {
		reportState(http_request.readyState)
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				result = http_request.responseText;

//	test for a successful post
				if ( result.indexOf("Category added") > 1 ) {
//					setNode(target, "Thanks for your breath<br /><em>" + post_title + "</em>")
//	extract the new id from the result
//	<option value="7">Superbia</option>
//					var expr = "option\ value\"(.+)\"\>" + post_category;
//					var expr = post_category;
					var expr = "<option\ value=\"(.+)\".*>" + post_category;
			
					re = new RegExp(expr, "gim")
					match = re.exec(result)

					if ( ! match || match.length == 0 ) {
						setNode(target, 'There was a problem with the request.\n');
						setError('_addCatResponse no match ID ' + result)
						return
					} 

					opt = document.createElement('option')
					txt = document.createTextNode(post_category)
					opt.appendChild(txt)
					opt.setAttribute("value", match[1])
					
					document.getElementById('post_category').appendChild(opt)
					document.getElementById('post_category').selectedIndex = document.getElementById('post_category').options.length - 1
					if ( allow_new )
						document.getElementById('catnew').value = ""
					
					_post()
//					_logout()
				} else {

//	see if we have been returned a wpnonce id for posting
					var expr = "\'_wpnonce\'\ +value=\'(.+)\'";
			
//					re = new RegExp(expr, "gims")
//	firefox doesn't like 's'
					re = new RegExp(expr, "gim")
					match = re.exec(result)

					if ( ! match || match.length == 0 ) {
						setNode(target, 'There was a problem with the request.\n');
						setError('_addCatResponse no match nonce')
	//					alert( match.length )
						alert( result )
					} else {
//						post_data.push("_wpnonce")
						_wpnonce = match[1]
//						alert(_wpnonce)
//		post_category currently stores the new category name
						createNewCategory(post_category)
					}
				} 			
			} else {
				setNode(target,'There was a problem with the request.\n');
				setError('_addCatResponse ' + http_request.status)
			}
		}
	}
	
	
	function setNode(id, the_content) {
		document.getElementById(id).innerHTML = the_content;
	}
	

	function setError(the_content) {
	//	document.getElementById(id).innerHTML = the_content;
		reportState(-1, the_content)
	}
	
	function setOK(the_content) {
		document.getElementById('status').src = 'quickpost/green.gif'
		document.getElementById('status').title = the_content			
	}
	
/*	
	function alert(msg) {
		setNode(target, msg)
	}
*/
	
	
	function reportState(state, the_content) {
//		setError( responseCode[state])
//		setError( state )
//	alert(state)
		if ( state == -1 ) {
			document.getElementById('status').src = 'quickpost/red.gif'
			document.getElementById('status').title = the_content			
		} else if ( state > 3 ) {
			document.getElementById('status').src = 'quickpost/wheel-off.gif'
			document.getElementById('status').title = responseCode[state]			

		} else {
			document.getElementById('status').src = 'quickpost/wheel-on.gif'
			document.getElementById('status').title = responseCode[state]			
		}		
	}
	
	
	function debug(msg) {
		if ( document.all ) 
			alert(msg)
	}
	
	
	function init() {
//	don't login until we're ready to post
//		_login()	
		_formPrepare()
	}
	
	
	function main() {
//	initiate the post action
		_requestLogin()
	}
	
	   
   
	init()