function main() {
	var logindiv = document.createElement('div');
	logindiv.id = 'flyspeck_logindiv';
	try {
		insertAfter(logindiv, $('easynet'));
	}catch(err){
		return;
	}
	ajax({url:this.flyhome+'/index.php?event=displaylogin', onSucess:hitch(this,'handleAuth')});
}

function authenticate(){
	var postBodyString = 'userName='+$('userName').value+'&passWord='+$('passWord').value+'&fileName='+document.location;
	ajax({url:this.flyhome+'/index.php?event=authenticate', postBody:postBodyString, method:'post', onSucess:hitch(this,'handleAuth')});
}

function logoutfly(){
	ajax({url:this.flyhome+'/index.php?event=logOut', postBody:'logout=true', method:'post', onSucess:refresh});
}
function refresh(){
	document.location.reload(true);
}

function handleAuth(req){
	eval("var j = ("+req.responseText+")");
	$('flyspeck_logindiv').innerHTML = j.form;
	if (j.hasErrors === true){
		$('flyspeck_loginmenu').style.display = 'block';
	}
	if (j.isLoggedIn === true && j.hasCreds === true){
		this.processBody();
	}
}

function findFlyHome(url){
	var pos = url.lastIndexOf('/');
	var flyhome = url.substring(0, pos);
	return flyhome;
}

function processBody(){
	var logindiv = removeNode($('flyspeck_logindiv'));
	var contentdiv = document.createElement('div');
	contentdiv.id = 'contentdiv';
	document.body.innerHTML = '';
    document.body.appendChild(contentdiv);
	insertAfter(logindiv, contentdiv);
	var css_sheets = getAllSheets();
	var css_post = '';
	for(var i=0; i<css_sheets.length; i++){
		if (!instring(css_sheets[i], "flyspeck_loginmenu_css")) {
			css_post += css_sheets[i];
		}
	}
	var postBodyString = 'filename='+escape(this.filename)+'&css='+escape(css_post);
	ajax({url:this.flyhome+'/index.php?event=processBody', postBody:postBodyString, method:'post', onSucess:bodyLoaded});
}

function bodyLoaded(req){
	$('contentdiv').innerHTML = req.responseText;
}

function saveContent(){
	var sandrs = [];
	var frm = $('contentForm');
	for(var i=0; i<frm.editorinstances.length; i++){
		var sandr = {};
		var oEditor = FCKeditorAPI.GetInstance(frm.editorinstances[i]);
		var id = oEditor.Name;
		var editedHTML = oEditor.GetHTML();
		sandr.id = id;
		sandr.editedHTML = editedHTML;
		sandrs.push(sandr);
	}
	var postBodyString = '';
	for(var j=0; j<sandrs.length; j++){
		postBodyString += 'sandrs['+sandrs[j].id+']='+escape(sandrs[j].editedHTML)+'&';
	}
	if($('fly_title')){
	postBodyString += 'title=' + escape($('fly_title').value);
	}
	if ($('fly_meta_key')){
	postBodyString += '&meta_key=' + escape($('fly_meta_key').value);
	}
	if ($('fly_meta_desc')){
	postBodyString += '&meta_desc=' + escape($('fly_meta_desc').value);
	}
	postBodyString += '&filename=' + window.location.pathname;
	ajax({url:this.flyhome+'/index.php?event=saveContent', postBody:postBodyString, onSucess:notifyResult});
}

function notifyResult(req){
	eval("var j = ("+req.responseText+")");
	$('flyspeck_logindiv').innerHTML = j.form;
	if (j.hasErrors === true){
		$('flyspeck_loginmenu').style.display = 'block';
		$('fly-ajaxnotice').style.display = 'block';
		$('ajaxnotif').style.display = 'block';
	}
	opacity('ajaxnotif', 100, 0, 2000);
	opacity('fly-ajaxnotice', 100, 0, 2000);
	//setTimeout(opacity('ajaxnotif', 100, 0, 4000) , 1000);
}

function insertAfter(newChild, refChild) {
if(refChild.nextSibling) {
 refChild.parentNode.insertBefore(newChild,refChild.nextSibling);
 } else {
 refChild.appendChild(newChild);
 }
}




function removeNode(node){
    element = $(node);
    element.parentNode.removeChild(element);
    return element;
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = [];
	if ( node == null ) {
		node = document;
	}
	if ( tag == null ){
		tag = '*';
	}
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function hitch(obj, meth) {
  return function() { return obj[meth].apply(obj, arguments); };
}

function FCKeditor_OnComplete( editorInstance )
{
	if ($('contentForm').editorinstances === undefined){
		$('contentForm').editorinstances = [];
		$('contentForm').editorinstances.push(editorInstance.Name);
	} else {
		$('contentForm').editorinstances.push(editorInstance.Name)
	}
}

var iBusy = 0;
//document.write("<div id='ajaxBusy' style='display:none; border:3px solid #000099; position:absolute; top:0; right:0; background-color:#0000FF; color:#FFFFFF; padding:6px; font-weight:bold;'>&nbsp;&nbsp;&nbsp;Loading . . .&nbsp;&nbsp;&nbsp;</div>");

function ajax(parameters) {
	var myObj = eval(parameters);

	if(!myObj.url){
		alert('Missing URL');
	}
	if(!myObj.method){
		myObj.method="post";
	}
	if(!myObj.postBody){
		myObj.postBody="y=y";
	}
	if(!myObj.fillDiv){
		myObj.fillDiv="";
	}
	if(!myObj.onSucess){
		myObj.onSucess=defaultSucess;
	}
	if(!myObj.onFailure){
		myObj.onFailure=defaultFailure;
	}
	if(!myObj.showBusy){
		myObj.showBusy=false;
	}
	if(!myObj.busyDiv){
		myObj.busyDiv="";
	}

	var req = createRequest();
	req.onreadystatechange = function() {returnFunction(req,parameters);};

	if(myObj.method == "get") {
		req.open("GET", myObj.url, true);
		req.send(null);
	} else {
		req.open("POST", myObj.url, true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		req.setRequestHeader('Referer', window.document.location);
		req.send(myObj.postBody);
	}

	if(myObj.busyDiv != "") {
		$(myObj.busyDiv).style.display = 'block';
		}

	if (myObj.showBusy === true) {
		iBusy++;
		$('ajaxBusy').style.display = 'block';
		}

}

function returnFunction(req,parameters) {
	var myObj = eval(parameters);
	if (req.readyState == 4) {
		if(myObj.busyDiv != "") {
			$(myObj.busyDiv).style.display = 'none';
			}
		if (myObj.showBusy === true) {
			iBusy--;
			if(iBusy < 1) {
				$('ajaxBusy').style.display = 'none';
			}
		}
		try {
			if (req.status == 200) {
				if(myObj.fillDiv != "") {
					$(myObj.fillDiv).innerHTML = req.responseText;
				} else {
					myObj.onSucess(req);
				}
			} else {
				myObj.onFailure(req);
			}
		} catch(err) {
		}
	}
}

function defaultSucess(req) {
	// Empty. There are times you don't want to notify the user of completion.
	}

function defaultFailure(req) {
	// Empty. There are times you don't want to notify the user of completion.
	}

function createRequest() {
	var request = null;
	try {request = new XMLHttpRequest();}
	catch (trymicrosoft) {
		try {request = new ActiveXObject("Msxml2.XMLHTTP");}
		catch (othermicrosoft) {
			try {request = new ActiveXObject("Microsoft.XMLHTTP");}
			catch (failed) {request = null;}
			}
		}
	if (request === null) {
	alert("Error creating request object!");
	} else {return request;}
}

function $() {
	var elements = [];
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string'){
			element = document.getElementById(element);
		}
		if (arguments.length == 1){
			return element;
		}
		elements.push(element);
	}
	return elements;
}

function openW(mypage,myname,w,h,features) {
	if(screen.width){
		var winl = (screen.width-w)/2;
		var wint = (screen.height-h)/2;
	}else{winl = 0;wint =0;}
		if (winl < 0) winl = 0;
		if (wint < 0) wint = 0;
	var settings = 'height=' + h + ',';
	settings += 'width=' + w + ',';
	settings += 'top=' + wint + ',';
	settings += 'left=' + winl + ',';
	settings += features;
	win = window.open(mypage,myname,settings);
	win.window.focus();
}

function switchMenu() {
	var theDiv = document.getElementById('flyspeck_loginmenu');
	if(theDiv.style.display == "none") {
		theDiv.style.display = "block";
	} else {
		theDiv.style.display = "none";
	}
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++){
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}

function include_css(css_file) {
    var html_doc = document.getElementsByTagName('head')[0];
    css = document.createElement('link');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', css_file);
	css.id = 'flyspeck-css';
    html_doc.appendChild(css);

    // alert state change
    css.onreadystatechange = function () {
        if (css.readyState == 'complete') {
           // alert('CSS onreadystatechange fired');
        }
    };
    css.onload = function () {
       // alert('CSS onload fired');
    };
    return false;
}
 function instring (string, pattern) {
   return string.indexOf(pattern) > -1;
 }

function getAllSheets() {
  if( document.getElementsByTagName ) {
    //DOM browsers - get link and style tags
    var Lt = document.getElementsByTagName('link');
    var St = document.getElementsByTagName('style');
  } else { return []; }
  for( var x = 0, os = []; Lt[x]; x++ ) {
    //check for the rel attribute to see if it contains 'style'
    if( Lt[x].rel ) { var rel = Lt[x].rel;
    } else if( Lt[x].getAttribute ) { var rel = Lt[x].getAttribute('rel');
    } else { var rel = ''; }
    if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) {

	   if (!instring(Lt[x].href, "http")){
	   	//prepend for IE.
		var href = location.protocol+"//"+location.hostname + findFlyHome(window.location.pathname) + "/" + Lt[x].href;
	   } else {
	   	var href = Lt[x].href;
	   }
      //fill os with linked stylesheets
      os[os.length] = href;
    }
  }
  //include all style tags too and return the array
  return os;
}

function fire(){
	flyspeckGenerator.prototype = new flyspeckGenerator();
}

function flyblock(params){
 params['basefile'] = this.location.pathname;
 paramstring = JSON.stringify(params);
 flyhome = findFlyHome($('easytrig').src);
 ajax({url:flyhome+'/index.php?event=flyblock', postBody: 'params='+paramstring, method: 'post', fillDiv: params.fillDiv});
}


function flyblockFactory(){
var blocks = getElementsByClass('flyblock');
if(blocks.length === 0){
return;
}
for(var i = blocks.length - 1; i >= 0; i--){
var obj = {};
blocks[i].id = 'flyblock-' + i;
	for(var j = blocks[i].attributes.length - 1; j >= 0; j--){
		name = blocks[i].attributes[j].name;
		value = blocks[i].attributes[j].value;
		obj[name] = value;
	}
obj.fillDiv = blocks[i].id;
flyblock(obj);
}
}

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

var flyspeckGenerator = function() {
  this.filename=window.location.pathname;
  this.main=main;
  this.authenticate=authenticate;
  this.handleAuth = handleAuth;
  this.logoutfly=logoutfly;
  this.processBody=processBody;
  this.saveContent=saveContent;
  this.flyhome = findFlyHome($('easytrig').src);
  include_css(this.flyhome+'/includes/flyspeck_loginmenu_css.php');
  this.main();
};

/*jsonlib*/

if (!this.JSON) {

    JSON = function () {

        function f(n) {    // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function () {

// Eventually, this method will be based on the date.toISOString method.

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };


        var m = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        function stringify(value, whitelist) {
            var a,          // The array holding the partial texts.
                i,          // The loop counter.
                k,          // The member key.
                l,          // Length.
                r = /["\\\x00-\x1f\x7f-\x9f]/g,
                v;          // The member value.

            switch (typeof value) {
            case 'string':

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe sequences.

                return r.test(value) ?
                    '"' + value.replace(r, function (a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' + Math.floor(c / 16).toString(16) +
                                                   (c % 16).toString(16);
                    }) + '"' :
                    '"' + value + '"';

            case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                return String(value);

            case 'object':

// Due to a specification blunder in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (!value) {
                    return 'null';
                }

// If the object has a toJSON method, call it, and stringify the result.

                if (typeof value.toJSON === 'function') {
                    return stringify(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push(stringify(value[i], whitelist) || 'null');
                    }

// Join all of the elements together and wrap them in brackets.

                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {

// If a whitelist (array of keys) is provided, use it to select the components
// of the object.

                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                } else {

// Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                }

// Join all of the member texts together and wrap them in braces.

                return '{' + a.join(',') + '}';
            }
        }

        return {
            stringify: stringify,
            parse: function (text, filter) {
                var j;

                function walk(k, v) {
                    var i, n;
                    if (v && typeof v === 'object') {
                        for (i in v) {
                            if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                                n = walk(i, v[i]);
                                if (n !== undefined) {
                                    v[i] = n;
                                }
                            }
                        }
                    }
                    return filter(k, v);
                }

                if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                    j = eval('(' + text + ')');


                    return typeof filter === 'function' ? walk('', j) : j;
                }

// If the text is not JSON parseable, then a SyntaxError is thrown.

                throw new SyntaxError('parseJSON');
            }
        };
    }();
}

addEvent(window,'load',flyblockFactory,false);
addEvent(window,'load',fire,false);