var QUOTES=new Array(3);
QUOTES[0]="Slices/images/Quote1.gif";
QUOTES[1]="Slices/images/Quote2.gif";
QUOTES[2]="Slices/images/Quote3.gif";
var QUOTEID=0;

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

//when something is clicked, this global is set so that mouseout does not deactivate it
var STRM = ""; //active stream within which an env is clicked 
//var STRMS = new Array("configuration", "master", "system_test","migration");
var ENV = ""; //active env
var MENU = new Array();
var OPT = new Array();
var ENVS = new Array ("cb","c8","c6","cr","br","c2","c4","c7","uat","m1","m2","m3","m4");
var i;
for (i=0;i<ENVS.length; i++){
	MENU[ENVS[i]] = ""; //active menu - this is  at the env evel so need to be associative
    OPT[ENVS[i]] = ""; //active menu - this is  at the env evel so need to be associative
}
var FORM = new Array();
FORM[0] = new Array("refr","refw","refi","desr","desw","desi","depi","modi","txts","txtw","txtr","txtt","txti");
FORM['fws'] = new Array("refw","refi","desw","desi","depi","txts","txti");
FORM['fwl'] = new Array("refw","refi","modi");
FORM['fwf'] = new Array("txtw","txti");
FORM['fwr'] = new Array("refw","refi");
FORM['frs'] = new Array("refr","refi","desr","desi","txts","txti");
FORM['frr'] = new Array("refr","refi");
FORM['frf'] = new Array("txtr","txti");
FORM['ftf'] = new Array("txtt","txti");
FORM['ffs'] = new Array("txts","txti");
var FORMTYPE = "";

var LogStat = new Array();
//var MENUS = new Array("webtracs","config","releases","replication","dba","system");
//var OPT = ""; //active option, suffix only this shoiuld be all we need to stick
//var OPTS = new Array("history", "history_f", "pending", "summary", "view", "cut", "deploy", "sync", "unsync", "rollback", "find", "builds", "builds_f","patches","viewbuild","release","replicate","counts","diff", "refresh","enable","compile","analyse","disable","rebuild","sort","classify");

//moved these ones here as they are the ones we are uing for this site

function nextQuote(target_id,img_base){
	var log = GetID(target_id); 
	//make sure we always load a valid image or the first in the list
	if (QUOTEID > 0){
		QUOTEID = (QUOTEID < QUOTES.length) ? QUOTEID : 0;
	}
	//alert("reloading quoted id " + QUOTEID + " out of " + QUOTES.length);
//	log.innerHTML = '<img src="new/' + QUOTES[QUOTEID] + '">'  ;
	log.innerHTML = '<img src="' + img_base + QUOTES[QUOTEID] + '">'  ;

	QUOTEID += 1;
	return;
}
// document.getElementById("div1").style.backgroundImage = "url(images/blue.gif)";

function setBgImage(url,target_id){
	//alert("changing menu bg image to " + url);
	var log = GetID(target_id);
	log.style.backgroundImage = "url(" + url + ")";
	//"url(" + url + ")";
}
function loadImage(url,target_id){
	var log = GetID(target_id);   
	log.innerHTML = '<img src="new/' + url + '">'  ;
 	return;
}
function loadContent(url,target_id) {
//alert("loading " + url + " to " + target_id);
    var ajax = initXMLHttpClient();
    if (!ajax){
        alert("ajax called failed, huh?. try a different browser!");
        return;
    }
    var log = GetID(target_id);   //new instance
    var data;

    ajax.onreadystatechange = function(){
        //log.innerHTML = "<h1>results pending..., please wait";
             //alert(ajax.readyState);
        if (ajax.readyState == 4) {
            log.innerHTML = ajax.responseText;
        }
    }
    ajax.open('GET',url, true);
    ajax.send(null);
}



//fisrt we hover on something that is clickable. there is no memeory
//type = busy/pointer/default for now and only applicable when set to tru
function Pointer(type){
	document.body.style.cursor=type;
	return true;
}
//the coluoits need to be built into a wrapper
function Hover(id){
	Color(id,'#FFFFCC');
	return Pointer('pointer');
}
//withno  hover, not only do we need to know what your id is, we need to know whoat group you are in
//we have differen fucntos for this
function NoHover(id){	
	Color(id,'transparent');
	return Pointer('default');
}
function ClickEnv(id,grp){
	var el;
	ShowID('manual',false); //jut in case help was clicked?
	if ((ENV.length == 0) || (ENV != id)){  //change detected
        if (ENV.length != 0){ //hide this one
    		el = ENV + "_env";
            ShowID(el,false);
            NoHover(STRM);
            InActive(ENV);
        }
        ENV = id; //new kid
        Active(ENV);
        el = id + "_env";
        ShowID(el,true);
		STRM = grp;
		Hover(grp);
	}
}
//similar to teh one above except we track associatively - that's a word right?
//you cannot reach this guy until ENV is set
//thsi i scalled not with real ids but relative ids and teh real id has to bne constructred with env_ + id
//the idea is., we nly really need to work on teh visible div and not all of them
//the previous state should bre preseeved autonaltically
function ClickOpt(opt,menu){
    var el;
    if ( (OPT[ENV].length == 0) || (OPT[ENV] != opt) ){ //change detected, animate
        if (OPT[ENV].length != 0){//deactivae this one
            el = ENV + "_" + OPT[ENV];
            InActive(el,false);
            el = ENV + "_" + MENU[ENV];
            NoHover(el);
        }
        MENU[ENV] = menu;
        el = ENV + "_" + menu;
        Hover(el);
        OPT[ENV] = opt;
        el = ENV + "_" + opt;
        Active(el);
    }
//now, we should be able to construct the deatil from the optio really.
//the  consrtuction makssit hard to read the code though or does it?
	return ExecuteOpt();
}

function ExecuteOpt(){
    var match = /_f/;  //this means that this option requires a form
    var req = OPT[ENV].split("_");
    if (match.test(OPT[ENV])){
	    setInput('request',req[0]);
	    return ShowForm(req[1]);
	        //return PostForm(); this is doen by the go-button on teh formmm
    }
    //hide the form we do not need it
    var id = ENV + "_input";
    ShowID(id,false);
    id = ENV + "_log";
    ShowID(id,true);

//okay we need to create the parameters to be sent and send it immediatiatl as a url encoded
//all we have is the environmen and the request like history
    var parameters = 'request=' + encodeURI(req[0]);
    parameters += '&env=' + ENV;
    send_request(parameters);
    return true;
}
function ShowForm(ftype){
    FORMTYPE=ftype;
    var mainid = ENV + "_input";
	ShowID(mainid,false) ; //hide the form and prepare it
//hide all ids
	var i;
	var el;
	var allids = FORM[0];
	for (i=0; i < allids.length ; i++){
		el = ENV + "_" + allids[i];
		ShowID(el,false);
	}
//get the form bits we want ofr thsi option
	allids = FORM[ftype];
	for (i=0; i < allids.length ; i++){
        el = ENV + "_" + allids[i];
        ShowID(el,true);
	}
    //hide log
    el = ENV + "_log";
    ShowID(el,false);
    ShowID(mainid,true);
}
function Active(id){
         Color(id,'#D9DB56');
}
function InActive(id){
         Color(id,'white');
}
//we can now hover and no hover ofr opt which now has a context based on env
function HoverMenu(menu){
	var id = ENV + "_" + menu;
	return Hover(id);
}
//i am not sure this is enough especially when we swicth environments
function NoHoverMenu(menu){
	if (MENU[ENV] != menu){
		var id = ENV + "_" + menu;
		NoHover(id);
	}
}
function NoHoverStream(id){
	if (STRM != id){
		NoHover(id);
	}
}
function initXMLHttpClient() {
    var xmlhttp;
    var e;
    try {
        // Mozilla / Safari / IE7
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        // IE
        var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                'MSXML2.XMLHTTP.4.0',
                'MSXML2.XMLHTTP.3.0',
                'MSXML2.XMLHTTP',
                'Microsoft.XMLHTTP' );
        var success = false;
        for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
            try {
                xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                success = true;
            } catch (e) {}
        }
        if (!success) {
            throw new Error('Unable to create XMLHttpRequest.');
        }
    }
    return xmlhttp;
}
function Color(id,bgcol){
    var el = GetID(id);
    if (el){
    	el.style.backgroundColor = bgcol;
        return;
    }
    alert (id + " -  id not found, colour not set") ;
}
function GetID(id){
    var elem;
    if( document.getElementById ) // this is the way the standards work
        elem = document.getElementById(id);
    else if( document.all ) // this is the way old msie versions work
        elem = document.all[id];
    else if( document.layers ) // this is the way nn4 works
        elem = document.layers[id];
    return elem;
}
function ShowID( id, show ){
    var elem = GetID(id);
    if(elem){
        var vis = elem.style;
        vis.display = (show) ? 'block' : 'none';
    }
}
function inputValue(name){
    var form_id = ENV + "_form";
    var form = GetID(form_id);
    var elems = form.elements;
    return elems[name].value;
}
function setInput(name,value){
    var form_id = ENV + "_form";
    var form = GetID(form_id);
    var elems = form.elements;
//alert("looking for " + name + " in " + form_id);
    elems[name].value = value;
}
//this needs review now.
function CheckForm(){
    //fytype tells us wht form we are checking and what is visible
    var	fields = FORM[FORMTYPE];
    var match = /i$/;
    var data;
    var passed = true;
    var el;
    var elid;
    var fname;
    for (i=0; i < fields.length ; i++){
//alert ("checking form field " + fields[i]);
            if (!match.test(fields[i])){
                 continue;
            }
        //this is an input field, for now, it cannot be empty
            el = fields[i];
            fname = el.replace(match,"");
            elid = ENV + "_" + el;
            data = inputValue(fname);
            if (isBlank(data)){
                passed = false;
            }
    }
    if(!passed){
        alert("Please provide information for all fields");
    }
    return passed;
}
function PostForm() {
    if (!CheckForm()){
        return;
    }
    var form_id = ENV + '_form';
        //url encode the form
    var form = GetID(form_id);
    //var parameters = new String;
    var parameters = "";
    var field;
    var val;
    var i;
    var regex = /go|button|tables|where|copy/;
    var option = inputValue('request');
    for (i=0; i < form.length; i++){
        field = form[i];
        if (regex.test(field.name)){
            continue;
        }
        if ((field.name == 'description') || (field.name == 'filter')){
            val =  field.name + '=' + inputValue(field.name);
        } else {
            val =  field.name + '=' + encodeURI(inputValue(field.name));
        }
        if (i == 0){
              parameters += val;
        } else {
              parameters += '&' + val;
        }
    }
    send_request(parameters);        
    form.reset();  //we just want to grey out the form to show that it has been used,
			// other than that, we want to keep the contents.
		   //this has to be managed cxaerefully to ensure there is no overlpa
    //var opts = env + "_options";
    //ShowID(opts,false);
    var el = ENV + "_input";
    ShowID(el,false);
    el = ENV + "_log";
    ShowID(el,true);
}

function send_request(parameters) {
alert("sending " + parameters);
//    var url = 'http://lonita1.kenan.com:6271/' + env ;
    var url = "/";
    var target_id = ENV + '_log';
    if (LogStat[target_id]){
        alert("results are pending please be patient. why don't you go and get a coffee or something...");
        return;
    }
    var ajax = initXMLHttpClient();
    if (!ajax){
        alert("ajax called failed, huh?. try a different browser!");
        return;
    }
    LogStat[target_id] = true;
    var log = GetID(target_id);   //new instance
    var init_tag = /^__INIT_CDM_STREAM__/;
    var data;

    ajax.onreadystatechange = function(){
        log.innerHTML = "<h1>results pending..., please wait";
             //alert(ajax.readyState);
        if (ajax.readyState == 4) {
            log.innerHTML = "<p>Done!</p>";
            data  = ajax.responseText;
            if (init_tag.match(data)){ //request from server to stream
                var stream_id = data.split("=");
                StreamLog(log,target_id,stream_id[1]); //this streams untnil done
            } else { //normal request we have all the data
                log.innerHTML = ajax.responseText; //okay this could say something like - request submitted
            }
            LogStat[target_id] = false; //allow another refresh
        }
    }
    ajax.open('POST',url, true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("Content-length", parameters.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.send(parameters);
}
function StreamLog(log,target_id, strm){
    var ajax =  initXMLHttpClient();
    if (!ajax){
        alert("ajax called failed, huh?. try a different browser!");
        return;
    }
    var end_tag = /^__END_CDM_STREAM__/;
    var data;
    ajax.onreadystatechange = function(){
        if (ajax.readyState == 4) {
            data = ajax.responseText;
            if (!end_tag.match(data)){ //there is more data, dump this and go again
                log.innerHTML += data;
                setTimeout(StreamLog(log,target_id,strm), 1000);
            }
            LogStat[target_id] = false; //allow another refresh
        }
    }
    ajax.open('GET',ENV + "_STREAM/" + strm, true);
    ajax.send(null);
}
function Ip(){
    var ip = new java.net.InetAddress.getLocalHost();
    var ipStr = new java.lang.String(ip);
    document.writeln(ipStr.substring(ipStr.indexOf("/")+1));
}
function ShowIDs(env,list,flag){
    var el;
    var i;
    for (i = 0; i <= list.length; i++){
        el = env + list[i];
        ShowID(el,flag);
    }
}
function isBlank(str){
    var regex = /([a-zA-Z0-9])/;
    return !regex.test(str);
}
function updateClock(){
  var currentTime = new Date();

  var currentHours = currentTime.getHours();
  var currentMinutes = currentTime.getMinutes();
  var currentSeconds = currentTime.getSeconds();
  var currentDayName = weekday[currentTime.getDay()]
  var currentDay = currentTime.getDate();
  var currentMonth = currentTime.getMonth() + 1;
// Pad the minutes and seconds with leading zeros, if required
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
  currentDay = ( currentDay < 10 ? "0" : "" ) + currentDay;
  currentMonth = ( currentMonth < 10 ? "0" : "" ) + currentMonth;  

// Choose either "AM" or "PM" as appropriate
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

  // Convert the hours component to 12-hour format if needed
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

  // Convert an hours component of "0" to "12"
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

  // Compose the string for display
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
  var currentDateString = currentDayName + " " + currentDay + "/" + currentMonth + "/" + currentTime.getFullYear() + " ";
  var el = GetID('clock');
  el.innerHTML = '<p>' + currentDateString + currentTimeString + '</p>';
  // Update the time display
 // document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

