//global variable
var _info = navigator.userAgent; 
var _ff = false;
var _mz = false;
var _ns = false;
var _op = (_info.indexOf("Opera") > 0);
var _ie = (_op == false
   				&& (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0
       			&& _info.indexOf("Windows 3.1") < 0));
// separate firefox and mozilla from netscape
_ff = (navigator.appName.indexOf("Netscape") >= 0 && _info.indexOf("Firefox") > 0);
_mz = (_ff == false 
   			&& navigator.appName.indexOf("Netscape") >= 0
   			&& (_info.indexOf("Netscape") <= 0 && _info.indexOf("Gecko") > 0));
_ns = (_ff == false && _mz == false 
   			&& navigator.appName.indexOf("Netscape") >= 0
   			&& ((_info.indexOf("Win") > 0 && _info.indexOf("Win16") < 0
        		&& java.lang.System.getProperty("os.version").indexOf("3.5") < 0)
       		|| _info.indexOf("Sun") > 0));


function openWaitWindow()
{
	waitWnd = window.open("", "WaitWindow", "width=150,height=100,toolbar=no,menubar=no,location=no,titlebar=no,scrollbars=no,resizable=no,status=no");
    if (waitWnd != null) 
    {
       	if (waitWnd.opener == null)
       	{
          	waitWnd.opener = self;
       	}
       	waitWnd.opener.document.mainForm.updated.value = "false";

       	var newContent = "<html><head>";
       	newContent += "<title>Loading Page</title>";
       	newContent += "<SCRIPT language=\"JavaScript\">";
       	newContent += "var timerID = null;";
       	newContent += "function startCount() {";
       	//newContent += "   alert(window.opener.document.mainForm.updated.value);";
       	newContent += "   timerID = setTimeout(\"closeThisWnd()\",1000);";
       	newContent += "}";
       	newContent += "function closeThisWnd() {";
       	//newContent += "   alert(window.opener.document.mainForm.updated.value);";
       	newContent += "   if (!window.opener || window.opener.closed || window.opener.document.mainForm.updated.value == \"true\") {";
       	newContent += "       clearTimeout(timerID);";
       	newContent += "       self.close();";
       	newContent += "   } else {";
       	newContent += "       timerID = setTimeout(\"closeThisWnd()\",1000);";
       	newContent += "   }";
       	newContent += "}";
       	newContent += "</SCRIPT>";
       	newContent += "</head>";
       	newContent += "<body onLoad=\"startCount();\" text=\"cyan\" bgcolor=\"black\"><center><font size=\"4\"><b>Loading page...</b></font>";
       	newContent += "<p><b>Please wait.</b></center></body></html>";
       	waitWnd.document.write(newContent);
       	waitWnd.document.close();
    }
}

function checkPopupBlocker() 
{
	// open the window in an invisible area to do the check
   	var oWin = window.open("","testpopupblocker","width=100,height=100,top=5000,left=5000");
   	if (oWin==null || typeof(oWin)=="undefined") 
   	{
   		alert("You HAVE A POPUP BLOCKER");
      	return true;
   	}
   	else 
   	{
      	oWin.close();
      	return false;
   	}
}

function OnMainLoad()
{
}

function OnMainUnLoad()
{
	if (window.winAddModules && !window.winAddModules.closed) {
		window.winAddModules.opener = null;
		window.winAddModules.close();
		window.winAddModules = null;
	}
	if (window.winEditModule && !window.winEditModule.closed) {
		window.winEditModule.opener = null;
		window.winEditModule.close();
		window.winEditModule = null;
	}
	if (window.winSaveProfile && !window.winSaveProfile.closed) {
		window.winSaveProfile.opener = null;
		window.winSaveProfile.close();
		window.winSaveProfile = null;
	}
	if (window.waitWnd && !window.waitWnd.closed) {
		window.waitWnd.opener = null;
		window.waitWnd.close();
		window.waitWnd = null;
	}
	if (window.winChangePswd && !window.winChangePswd.closed) {
		window.winChangePswd.opener = null;
		window.winChangePswd.close();
		window.winChangePswd = null;
	}
	if (window.winResetPswd && !window.winResetPswd.closed) {
		window.winResetPswd.opener = null;
		window.winResetPswd.close();
		window.winResetPswd = null;
	}
	if (window.winSaveSettings && !window.winSaveSettings.closed) {
		window.winSaveSettings.opener = null;
		window.winSaveSettings.close();
		window.winSaveSettings = null;
	}
}

// actions include: moving up, down, left and right
// NOTE: x is really "ROW" and y is really "COLUMN"
function moveChart(movetype, x, y, item_number, right_border, lastrow, lastcol, lastitem) 
{
    var frm = document.mainForm;
        
	//frm.currtime.value = (new Date()).getTime();
	frm.moveType.value = movetype;
	frm.selChartRightBorder.value = right_border;
	frm.isSelChartInLastRow.value = lastrow;
	frm.firstPosX.value = x;
	frm.secondPosX.value = x;
	frm.firstPosY.value = y;
	frm.secondPosY.value = y;

	if (validateParams(movetype, x, y, lastrow, lastcol, lastitem)) {
	
    	if (setXYValues(movetype, x, y, item_number, lastrow)) {

			openWaitWindow();
	
			if (movetype == "up") {
	        	frm.action = "../UserPrefAction.do?task=doUpdate&subTask=up";
			} else if (movetype == "down") {
	        	frm.action = "../UserPrefAction.do?task=doUpdate&subTask=down";
			} else if (movetype == "left") {
	        	frm.action = "../UserPrefAction.do?task=doUpdate&subTask=left";
			} else if (movetype == "right") {
	        	frm.action = "../UserPrefAction.do?task=doUpdate&subTask=right";
			} else {
				return; //invalid action
			}
			
			frm.target = "work";
	     	frm.submit();
	     	
     	} else {
     		window.alert("An error occured when moving the chart.");
     	}
	} else {
        window.alert("The module has reached the border for the direction requested.");
	}
}

//NOTE: x is really "ROW" and y is really "COLUMN"
function validateParams(movetype, x, y, lastrow, lastcol, lastitem) 
{
	var frm = document.mainForm;
	
	var nTickerCount = 0;
	var tickerCount = frm.tickerCount.value;
	if (tickerCount != null && tickerCount.length > 0)
	  	nTickerCount = parseInt(tickerCount);
	if (movetype == "up" && nTickerCount > 0) {
	  	// if a ticker exists, treat row 1 as row 0
	  	x = x - 1;
	}
	
	if ((movetype == "up" && x != 0)
	    || (movetype == "left" && y != 0)
	    || (movetype == "right" && !lastcol)
	    || (movetype == "down" && !lastitem)
	    ) {
		return true;			
	} else {
		return false;
	}
}

//NOTE: x is really "ROW" and y is really "COLUMN"
function setXYValues(movetype, x, y, item_number, lastrow) 
{
	var frm = document.mainForm;
	
	var next_index = 0;
	if (movetype == "left") {
		frm.firstPosY.value = y - 1;
	} else if (movetype == "right") {
		frm.secondPosY.value = y + 1;
	} else if (movetype == "up") {
		next_index = getNextElementIndex(item_number, -1);
		if (next_index >= 0) {
			frm.firstPosX.value = frm.rows[next_index].value;
			frm.firstPosY.value = frm.columns[next_index].value;
		}
	} else if (movetype == "down") {
		if (lastrow == "false") {
			next_index = getNextElementIndex(item_number, 1);
			if (next_index >= 0) {
				frm.secondPosX.value = frm.rows[next_index].value;
				frm.secondPosY.value = frm.columns[next_index].value;
			}
		} else {
			frm.secondPosX.value = x + 1;
			frm.secondPosY.value = 0;
		}
	}
	if (next_index == -1) {
		return false; //just in case
	} else {
		return true;
	}
}

function getNextElementIndex(item_number, delta) 
{
	if (item_number < 0) {
		return -1;
	}
	
	var frm = document.mainForm;
    var next_element = -1;
	var prev_item = -1;
	
	//Selected item row
	var item_row = frm.rows[item_number].value;
	//Selected item right border position
	var item_point = frm.chartRightBorders[item_number].value;
	
	//Get previous element index
	if (delta == -1) {
		// for moving "up"
		prev_item = item_number - frm.columns[item_number].value - 1;
	} else {
		// for moving "down"
		for (var j=1; prev_item == -1; j++) {
			if(item_row != frm.rows[item_number + j].value) {
				prev_item = item_number + j;
			}
		}
	}
	//Get "upper" or "lower" element index
	for (var i=0; next_element == -1; i++) {
		
		var w1 = 0;
		var next_el_row = -1;
		
		//Get next element right position
		if ((prev_item + (delta*i)) >= 0) {
			w1 = frm.chartRightBorders[prev_item + (delta*i)].value;
		}
		
		//Check if next element has another next element and get its row
		if ((prev_item +delta*(i+1)) >= 0 && frm.rows[prev_item +delta*(i+1)]) {
			next_el_row = frm.rows[prev_item +delta*(i+1)].value;
		}
		// Check if it is a last element to be processed
		if ((parseInt(item_row)+parseInt(delta)) != parseInt(next_el_row)) {
			next_element = prev_item + (delta*i);
		} else {
			//Get next element left postion
			var w0 = 0;
			//Check if it is a first element for "down"
			if (delta != 1 || i != 0) {
				//if not, get its value (otherwise it is 0)
				if ((prev_item + (delta*i) - 1) >= 0) {
					w0 = frm.chartRightBorders[prev_item + (delta*i) - 1].value;
				}
			}
			//Check if element width is "out of scope" of first/last element of upper row for "up
			if (delta == -1 && i == 0 && parseInt(item_point) > parseInt(w1)) {
				next_element = prev_item;
			}
			//item_point is within next element borders
			if (parseInt(item_point) > parseInt(w0) && parseInt(item_point) <= parseInt(w1)) {
				next_element = prev_item + (delta*i);
			}
		}
	}
	return next_element;
}
	
function changeOpenProfile()
{
    var frm = document.mainForm;
    var selOpenProfile = frm.profile.options[frm.profile.selectedIndex].value;
    var profileText = selOpenProfile;
    if (profileText == "4")
       	profileText = "Default";
    if (confirm("Are you sure you want to open profile " + profileText + " ?"))
    {
    	openWaitWindow();

		frm.target = "work";
        frm.action = "../UserPrefAction.do?task=update";
     	frm.submit();
    }
	else
    {
       	for (var i = 0; i < frm.profile.length; i++)
       	{
          	if (frm.profile.options[i].defaultSelected)
          	{
             	frm.profile.selectedIndex = i;
          	}
       	}
    }
}

function changeSaveAsProfile()
{
    var frm = document.mainForm;
    var selSaveProfile = frm.saveAsProfile.options[frm.saveAsProfile.selectedIndex].value;
    if (selSaveProfile == "0")
    {
       	alert ("Please select a profile to save as.");
       	frm.saveAsProfile.focus();
    }
    else
    {
       	if (confirm("Are you sure you want to save the screen as profile " + selSaveProfile + " ?"))
       	{
		  	//open a new window and show the contents to it
            winSaveProfile = window.open("", "NewWindowForSave", "width=150,height=100");
            if (winSaveProfile != null)
            {
               	if (winSaveProfile.opener == null)
               	{
                  	winSaveProfile.opener = self;
               	}
               	//winSaveProfile.moveTo(400,300);

               	var newContent = "<html><head><title>Saving...</title></head>";
               	newContent += "<body text=\"cyan\" bgcolor=\"black\"><center><font size=\"4\"><b>Saving profile...</b></font>";
               	newContent += "<p><b>Please wait.</b></center></body></html>";
               	winSaveProfile.document.write(newContent);
               	winSaveProfile.document.close(); //close layout stream
            }
            
            frm.target = "NewWindowForSave";
            frm.action = "../UserPrefAction.do?task=doUpdate&subTask=saveProfile";
            frm.submit();
       	}
       	else
       	{
          	for (var i = 0; i < frm.saveAsProfile.length; i++)
          	{
             	if (frm.saveAsProfile.options[i].defaultSelected)
             	{
                	frm.saveAsProfile.selectedIndex = i;
             	}
          	}
       	}
    }
}

function clickAddModule()
{
    var frm = document.mainForm;
	winAddModules = window.open("", "addModules", "scrollbars,resizable,width=700, height=400");
	if (winAddModules != null)
    {
       	if (winAddModules.opener == null)
       	{
          	winAddModules.opener = self;
       	}
		frm.target = "addModules";
		frm.action = "../UserPrefAction.do?task=insert";
  		frm.submit();
  	}
}

function clickEditModule(chartid)
{
    var frm = document.mainForm;
	winEditModule = window.open("", "editModule", "scrollbars,resizable,width=500, height=250");
	if (winEditModule != null)
    {
       	if (winEditModule.opener == null)
       	{
          	winEditModule.opener = self;
       	}
		frm.target = "editModule";
		frm.action = "../UserPrefAction.do?task=edit&selChartID=" + chartid;
  		frm.submit();
  	}
}

function clickClose(chartid)
{
   	if (!confirm('You are about to close the module. \n Do you wish to continue?'))
   	{
   		return;
   	}
   	var frm = document.mainForm;
   	
   	frm.selChartID.value = chartid;
   	
   	openWaitWindow();

	frm.target = "work";
    frm.action = "../UserPrefAction.do?task=doDelete";
    frm.submit();
}

function clickChangePassword()
{
    var frm = document.mainForm;
	winChangePswd = window.open("", "changePswd", "scrollbars,resizable,width=800, height=200");
	if (winChangePswd != null)
    {
       	if (winChangePswd.opener == null)
       	{
          	winChangePswd.opener = self;
       	}
		frm.target = "changePswd";
		frm.action = "../PasswordChange.do?task=update";
  		frm.submit();
  	}
}

function clickResetPassword()
{
	var frm = document.mainForm;
	winResetPswd = window.open("", "resetPswd", "scrollbars,resizable,width=700, height=200");
	if (winResetPswd != null)
    {
       	if (winResetPswd.opener == null)
       	{
          	winResetPswd.opener = self;
       	}
		frm.target = "resetPswd";
		frm.action = "../PasswordReset.do?task=update";
  		frm.submit();
  	}
}

function clickLogout()
{
    var frm = document.mainForm;
	frm.target = "work";
	frm.action = "../LoginAction.do?task=doLogout";
  	frm.submit();
}

function clickHelp()
{
	checkPopupBlocker();
    window.open("help/portalhelp.pdf");
}

function getListOfAllHourlyLMPNodes() {
	return document.mainForm.allHLMPNodesString.value;
}
function getListOfAll5MinRTLMPNodes() {
	return document.mainForm.all5MinLMPNodesString.value;
}
function getListOfAllHourlyReserveZonePricesNodes(){
    return document.mainForm.allHourlyReserveZonePriceNodesString.value;  
}
function getListOfAll5MinReserveZonePricesNodes(){
    return document.mainForm.all5MinReserveZonePriceNodesString.value;  
}
function getListOfAllInterfaces() {
	return document.mainForm.allInterfacesString.value;
}
function getListOfAllSYSLoadZones() {
	return document.mainForm.allSysLoadZonesString.value;
}
function getListOfAllLoadFCZones() {
	return document.mainForm.allLoadFCZonesString.value;
}
function getListOfAllWeeklyLMPNodes() {
	return document.mainForm.allWLMPNodesString.value;
}
function getListOfAllMonthlyLMPNodes() {
	return document.mainForm.allMLMPNodesString.value;
}
function getMaxDateInterval() {
	return document.mainForm.maxDateInterval.value;
}
function getMaxDateIntervalWLMP() {
	return document.mainForm.maxDateIntervalWLMP.value;
}
function getMaxDateIntervalMLMP() {
	return document.mainForm.maxDateIntervalMLMP.value;
}
function getMaxAreaComboBox() {
	return document.mainForm.maxAreaCombobox.value;
}
function getSwctCutOverDate() {
	return document.mainForm.swctCutOverDate.value;
}

function getChartID(item_number) {
	var frm = document.mainForm;
	var chartID = "0";
	if (frm.chartIDs[item_number] != null) {
		chartID = frm.chartIDs[item_number].value;
	} else {
		chartID = frm.chartIDs.value;
	}
	return chartID;
}
function saveSettings(item_number, action) 
{
	var frm = document.mainForm;
	var chartID = getChartID(item_number);
	
	//open a new window in an invisible aera (hide it) for saving the settings sillently
    winSaveSettings = window.open("", "NewWindowForSettings", "width=150,height=100,top=5000,left=5000");
    if (winSaveSettings != null)
    {
       	if (winSaveSettings.opener == null)
       	{
          	winSaveSettings.opener = self;
       	}
       	var newContent = "<html><head><title>Saving...</title></head>";
        newContent += "<body text=\"cyan\" bgcolor=\"white\"><center><font size=\"4\"><b>Saving settings...</b></font>";
       	newContent += "<p><b>Please wait.</b></center></body></html>";
       	winSaveSettings.document.write(newContent);
       	winSaveSettings.document.close(); //close layout stream
    }
    frm.target = "NewWindowForSettings";
    frm.action = "../UserPrefAction.do?task=doUpdate&subTask=" + action + "&ID=" + chartID;
    frm.submit();
}
function setDate(item_number, datefrom, dateto) 
{
	var frm = document.mainForm;
	if (frm.chartIDs[item_number] != null) {
		frm.dateFroms[item_number].value = datefrom;
		frm.dateTos[item_number].value = dateto;
		frm.toBeUpdateds[item_number].value = "true";
	}
	else {
		frm.dateFroms.value = datefrom;
		frm.dateTos.value = dateto;
		frm.toBeUpdateds.value = "true";
	}
	
	saveSettings(item_number, "saveDates");
}
function setAreas(item_number, areas, types, columns) 
{
	var frm = document.mainForm;
	if (frm.chartIDs[item_number] != null) {
		frm.areasStrings[item_number].value = areas;
		frm.dataTypesStrings[item_number].value = types;
		frm.dataColumnsStrings[item_number].value = columns;
		frm.toBeUpdateds[item_number].value = "true";
	}
	else {
		frm.areasStrings.value = areas;
		frm.dataTypesStrings.value = types;
		frm.dataColumnsStrings.value = columns;
		frm.toBeUpdateds.value = "true";
	}
	
	saveSettings(item_number, "saveAreaNType");
}
function setColumns(item_number, columns) 
{
	var frm = document.mainForm;
	if (frm.chartIDs[item_number] != null) {
		frm.dataColumnsStrings[item_number].value = columns;
		frm.toBeUpdateds[item_number].value = "true";
	}
	else {
		frm.dataColumnsStrings.value = columns;
		frm.toBeUpdateds.value = "true";
	}
	
	saveSettings(item_number, "saveColumn");
}

function getCSVData(url)
{
	checkPopupBlocker();
	document.location.href = url;
}
function nyzonemapInfo() 
{
	checkPopupBlocker();       
    var nymapInfoWnd = window.open("http://www.nyiso.com/public/markets_operations/market_data/maps/", "NYZoneMap");
    if (nymapInfoWnd != null) {
       	nymapInfoWnd.focus();
    }
}
function alertStatusInfo() 
{
	checkPopupBlocker();
    var alertInfoWnd = window.open("../AlertInfoList.do?task=doSearch", "AlertInfo", "scrollbars,width=600,height=500");
    if (alertInfoWnd != null) {
       	alertInfoWnd.focus();
    }
}

function morningReport () 
{
	checkPopupBlocker();
	window.open("/sys_ops/mornrpt/index.html");
}
function specialNotices () 
{
	checkPopupBlocker();
	window.open("/calendar/day.action?type=2");
}
function psConditions () 
{
	checkPopupBlocker();
	window.open("/psc/view.do");
}
function transmissionOutages () 
{
	checkPopupBlocker();
	window.open("/trans/ops/short_term/index.html");
}


