// The Site Editor V 1.0 - Tues, April 04, 2006
//
// Copyright © 2005-2006 Kyle Campbell - thesiteeditor.com - All Rights Reserved
//
// THIS COPYRIGHT INFORMATION MUST REMAIN INTACT
// AND MAY NOT BE MODIFIED IN ANY WAY
//
// When you purchased this script you agreed to accept the terms
// of this Agreement. This Agreement is a legal contract, which
// specifies the terms of the license and warranty limitation between
// you and 'thesiteeditor.com'. You should carefully read the following
// terms and conditions before installing or using this software.
// Unless you have a different license agreement arranged with 'KYLE CAMPBELL' of thesiteeditor.com,
// installation or use of this 
// software indicates your acceptance of the license and warranty
// limitation terms contained in this Agreement.
// If you do not agree to the terms of this Agreement, promptly delete
// and destroy all copies of the Software.
//
// Versions of the Software
// Only one licenced copy of the site editor  may be used on one web site.
//
// License to Redistribute
// Distributing the software and/or documentation with other products
// (commercial or otherwise) by any means without prior written 
// permission from 'thesiteeditor.com' or 'Kyle Campbell' is forbidden.
// All rights to the the site editor software and documentation not expressly
// granted under this Agreement are reserved to 'Kyle Campbell'.
//
// Disclaimer of Warranty
// THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" 
// AND WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY 
// OTHER WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE 
// VARIOUS HARDWARE AND SOFTWARE ENVIRONMENTS INTO WHICH THE SITE EDITOR
// MAY BE USED, NO WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE IS 
// OFFERED.  THE USER MUST ASSUME THE ENTIRE RISK OF USING THIS 
// PROGRAM.  ANY LIABILITY OF 'THESITEEDITOR.COM' WILL BE LIMITED 
// EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
// IN NO CASE SHALL 'THESITEEDITOR.COM' OR 'KYLE CAMPBELL' BE LIABLE FOR 
// ANY INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, 
// WITHOUT LIMITATION, LOST PROFITS OR THE INABILITY TO USE EQUIPMENT 
// OR ACCESS DATA, WHETHER SUCH DAMAGES ARE BASED UPON A BREACH OF 
// EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT, NEGLIGENCE, 
// STRICT TORT, OR ANY OTHER LEGAL THEORY.
// THIS IS TRUE EVEN IF 'THESITEDEDITOR.COM' OR 'KYLE CAMPBELL' ARE ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL 'THESITEDEDITOR.COM' 
// OR 'KYLE CAMPBELL'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE 
// FEE ACTUALLY PAID BY LICENSEE TO 'THESITEDEDITOR.COM' OR 'KYLE CAMPBELL'.
//
// Warning: This program is protected by copyright law. Unauthorized 
// reproduction or distribution of this program, or any portion of it,
// may result in severe civil and criminal penalties, and will be
// prosecuted to the maximum extent possible under the law.
//
// Credits:
// Kyle Campbell - Concept, Designer, Programmer
//
//
// Thank you for purchasing this script.
// If you have any suggestions or ideas please direct them to 
// cms@thesiteeditor.com
//

function Editor(_saver, _file ){
	var instance = this;
	this._saver = _saver;
	this._file = _file;
	this._blocks = [];
	this._divClass = 'editable';
	this._curBlock = null;
	this._curFrame = null;	
	this.findBlocks();
}

/* Show editable blocks */
Editor.prototype.viewBlocks = function(){
	this.addToolbar();
	for(var i in this._blocks){
		this._blocks[i].style.borderWidth = 1;
		this._blocks[i].style.borderStyle = 'dashed';
		this._blocks[i].style.borderColor = '#CD0505';
		this._blocks[i].style.cursor = 'pointer';
		this._blocks[i].style.float = 'bottom';
		addEvent("click", this._blocks[i], editContainer);
	}
}

/* hide editable blocks */
Editor.prototype.hideBlocks = function(){
	for(var i in this._blocks){
		this._blocks[i].style.borderWidth = 0;
		this._blocks[i].style.cursor = null;
	}
}

/* find editable blocks */
Editor.prototype.findBlocks = function(){
	var found = document.getElementsByTagName('DIV');
	for(var i in found){
		if(found[i].className == this._divClass){
			this._blocks[this._blocks.length++] = found[i];
		}
	}
}


/* start edit block */
Editor.prototype.editBlock = function(block){

	this.saveBlock(this._curBlock);
	/* create iframe element */
	iframe = document.createElement('IFRAME');
	iframe.frameBorder = 0;
	iframe.style.width = block.offsetWidth;
	iframe.style.height = block.offsetHeight;
	iframe.style.borderWidth = 1;
	iframe.style.borderStyle = 'dashed';
	iframe.style.borderColor = '#CD0505';
	iframe.style.backgroundColor = 'transparent';	
	iframe.scrolling='no';

	/* replace dive to iframe */
	block.parentNode.replaceChild(iframe, block);
	head = document.getElementsByTagName('HEAD')[0];

	/* copy data from div to iframe */
	var doc = '<html><head>'+head.innerHTML+'</head>';
	doc += '</head>\n<body marginwidth=0 leftmargin=0 topmargin=0 margintop=0>';
	doc += block.innerHTML;
	doc += '</body></html>';

	iframe.contentWindow.document.open();
	iframe.contentWindow.document.write(doc);
	iframe.contentWindow.document.close();	

	/* make iframe editable */
	if(document.all) iframe.contentWindow.document.body.contentEditable = "true";
	else iframe.contentWindow.document.designMode="on";

	iframe.style.borderColor = 'green';
	this._curBlock = block;
	this._curFrame = iframe;
}


/* save current block and convert it to div */
Editor.prototype.saveBlock = function(block){
	if(this._curFrame == null) return;
	block.innerHTML = this._curFrame.contentWindow.document.body.innerHTML;
	this._curFrame.parentNode.replaceChild(block, this._curFrame);
}


/* apply command to a selected text */
Editor.prototype.exec = function(command, ui, option){
	if(this._curFrame !=null ){
		this._curFrame.contentWindow.document.execCommand(command, ui, option);
	}
}

/* save all document */
Editor.prototype.save = function(){

	this.saveBlock(this._curBlock);
	this.hideBlocks();
	this.delToolbar();

	var body = document.getElementsByTagName('HTML')[0];
	form = document.createElement('FORM');
	form.method = 'POST';
	form.action = this._saver;

	hiddenBody = document.createElement('INPUT');
	hiddenBody.type = 'hidden';
	hiddenBody.name = 'body';
	hiddenBody.value = body.innerHTML;

	hiddenFile = document.createElement('INPUT');
	hiddenFile.type = 'hidden';
	hiddenFile.name = 'file';
	hiddenFile.value = this._file;

	form.appendChild(hiddenFile);
	form.appendChild(hiddenBody);
	body.appendChild(form);
	form.submit();
}

function openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

/* show toolbar */
Editor.prototype.addToolbar = function(){
	var div = document.createElement('DIV');
	div.width="100%";
	div.style.background = '#EEEFFF';

	html = '<table cellspacing=0 cellpadding=0 border=0 width=100% style=\'height:30px;\'><tr>';
	html += '<td style=\'padding-left:5px;\'><img src=\'editor/images/logo.gif\'></td>';
	html += '<td style=\'padding-left:5px;\'><a onMouseDown=\'editor.save();\'><img src=\'editor/images/save.gif\' border=\'0\' title=\"SAVE CHANGES!"></a></td>';
	html += '<td valign=top style=\'padding-left:5px;padding-right:2px;padding-top:3px;\'>|</td>';
	html += '<td><a onClick=\'editor.exec("bold", false, null);\'><img src=\'editor/images/bold.gif\' border=\'0\' title=\"Bold"></a></td>';
	html += '<td><a onClick=\'editor.exec("italic", false, null);\'><img src=\'editor/images/italic.gif\' border=\'0\' title=\"Italic"></a></td>';
	html += '<td><a onClick=\'editor.exec("underline", false, null);\'><img src=\'editor/images/underline.gif\' border=\'0\' title=\"Underline"></a></td>';
	html += '<td valign=top style=\'padding-left:2px;padding-right:5px;padding-top:3px;\'>|</td>';	
	html += '<td style=\'padding-right:5px;\'><select style=\'width:100px;\' id=\'fontName\' onChange=\'javascript:editor.exec("fontname",false, this.options[selectedIndex].value)\'>';
	html += '<option value=\'serif\' selected>Font name</option><option value=\'serif\'>Serif</option><option value=\'arial\'>Arial</option><option value=\'tahoma\'>Tahoma</option></select></td>';
	html += '<td><select style=\'width:100px;\' id=\'fontSize\' onChange=\'javascript:editor.exec("fontsize",false, this.options[selectedIndex].value);\'>';
	html += '<option value=\'9\'>Font size</option><option value=\'1\'>8</option><option value=\'2\'>9</option><option value=\'3\'>10</option><option value=\'4\'>11</option><option value=\'5\'>12</option><option value=\'6\'>13</option></select></td>';
	html += '<td valign=top style=\'padding-left:5px;padding-right:2px;padding-top:3px;\'>|</td>';	
	html += '<td><a onClick=\'editor.exec("justifyleft", false, null);\'><img src=\'editor/images/j_left.gif\' border=\'0\' title=\"Justify Right"></a></td>';
	html += '<td><a onClick=\'editor.exec("justifycenter", false, null);\'><img src=\'editor/images/j_center.gif\' border=\'0\' title=\"Center Text"></a></td>';
	html += '<td><a onClick=\'editor.exec("justifyright", false, null);\'><img src=\'editor/images/j_right.gif\' border=\'0\' title=\"Justify Right"></a></td>';
	html += '<td><a onClick=\'editor.exec("justifyfull", false, null);\'><img src=\'editor/images/justifyfull.gif\' border=\'0\' title=\"Justify Text\"></a></td>';
	html += '<td valign=top style=\'padding-left:5px;padding-right:2px;padding-top:3px;\'>|</td>';	
	html += '<td><a onClick=\'editor.exec("insertunorderedlist", false, null);\'><img src=\'editor/images/bullist.gif\' border=\'0\' title=\"Insert Bullet List\"></a></td>';
	html += '<td><a onClick=\'editor.exec("insertorderedlist", false, null);\'><img src=\'editor/images/numlist.gif\' border=\'0\' title=\"Insert Ordered List\"></a></td>';
	html += '<td valign=top style=\'padding-left:5px;padding-right:2px;padding-top:3px;\'>|</td>';
	html += '<td><a onClick=\'editor.exec("indent", false, null);\'><img src=\'editor/images/indent.gif\' border=\'0\' title=\"Indent\"></a></td>';
	html += '<td><a onClick=\'editor.exec("outdent", false, null);\'><img src=\'editor/images/outdent.gif\' border=\'0\' title=\"Outdent\"></a></td>';
	html += '<td valign=top style=\'padding-left:5px;padding-right:2px;padding-top:3px;\'>|</td>';
	html += '<td><a onClick=\'editor.exec("undo", false, null);\'><img src=\'editor/images/undo.gif\' border=\'0\' title=\"Undo\"></a></td>';
	html += '<td><a onClick=\'editor.exec("redo", false, null);\'><img src=\'editor/images/redo.gif\' border=\'0\' title=\"Redo\"></a></td>';
	html += '<td><a onClick=\'openBrWindow("editor/img.php","Images","width=700,height=540");\'><img src=\'editor/images/pic.gif\' border=\'0\' title=\"Manage Image\"></a></td>';
	html += '<td width=\'100%\' height=\'10\'></td></tr></table>';

	
	div.innerHTML = html;
	document.body.insertBefore( div, document.body.childNodes[0]);
}

// remove last first child from body
Editor.prototype.delToolbar = function(){
	document.body.removeChild(document.body.childNodes[0]);
}



/* bind editor event */
function editContainer(event){
	/* define event target */
	var target = null;
	if(window.event) target = window.event.srcElement;
	else target = event.target;
	/* find div element */
	while( target != null){
		if(target.className != 'editable'){
			target = target.parentNode;
		} else break;
	}

	/* bind click on div container */
	if(target != null && target.tagName == 'DIV'){
		for(index in editor._blocks){
			if(target == editor._blocks[index])
				editor.editBlock(editor._blocks[index]);
		}
	}	
}


/* resize current block */
function resize(){
	setTimeout("resize()", 10);
	if(editor._curFrame == null) return;
	if (editor._curFrame.contentWindow.document.body != null){
		with(editor._curFrame.contentWindow.document.body){
			if (offsetHeight && scrollHeight){
				if(document.all) editor._curFrame.style.height = scrollHeight;
				else{
					if((scrollHeight-8) - offsetHeight < 0)
						editor._curFrame.style.height = scrollHeight;
					else editor._curFrame.style.height = offsetHeight;
				}
			}
		}
	}
}



/* add some event to object */
function addEvent(event, object, method){
	if(object.addEventListener){
		object.addEventListener(event, method, false);
	} else object.attachEvent('on'+event, method);
}


function init(_saver, _file){
	editor = new Editor(_saver, _file);
	addEvent("keypress", document, startEditor);
	resize();
}

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
/* show editable blocks (shift+e) */
function startEditor(event){	
	if(window.event && window.window.event.keyCode == 69){
		var pass = window.prompt("Please enter your password","password");
		sndReq(pass);
	}
	else if(event.which && event.which == 69){
		var pass = window.prompt("Please enter your password","password");
		sndReq(pass);
	}
}
var http = createRequestObject();

function sndReq(pass) {
    http.open('get', 'editor/auth.php?action='+pass);
    http.onreadystatechange = handleResponse;
    http.send(null);
}
function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
				if (response == 'startauthentication'){
			alert('Access granted. Click the red boxes to edit.');
				editor.viewBlocks();
				}else{
					//alert(response);
					alert("You are not authorized to edit this site, please contact your webmaster.");
						}
        }
    }
