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($('flytrig').src);
  include_css(this.flyhome+'/includes/flyspeck_loginmenu_css.php');
  this.main();
};

function main() {
	var logindiv = document.createElement('div');
	logindiv.id = 'flyspeck_logindiv';
    document.body.appendChild(logindiv);
	ajax({url:this.flyhome+'/index.php?event=displaylogin', onSucess:hitch(this,'handleAuth')});
}

function authenticate(){
	ajax({url:this.flyhome+'/index.php?event=authenticate', postBody:'userName='+$('userName').value+'&passWord='+$('passWord').value, 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){
		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 = new Array();
	var frm = $('contentForm');
	for(var i=0; i<frm.editorinstances.length; i++){
		var sandr = new Object();
		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 i=0; i<sandrs.length; i++){
		postBodyString += 'sandrs['+sandrs[i].id+']='+escape(sandrs[i].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';
		$('ajaxnotif').style.display = 'block';
		opacity('ajaxnotif', 0, 100, 1000);
	}
	setTimeout("opacity('ajaxnotif', 100, 0, 1000)" , 4000);

}

function insertafter(newChild, refChild) {
 refChild.parentNode.insertBefore(newChild,refChild.nextSibling);
}

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

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

function FCKeditor_OnComplete( editorInstance )
{
	if ($('contentForm').editorinstances == undefined){
		$('contentForm').editorinstances = new Array();
		$('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 = new Array();
	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(divId) {
	var theDiv = document.getElementById(divId);
	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;
}

flyspeckGenerator.prototype = new flyspeckGenerator();
