// JavaScript Document
/*
function JumpToDate(form) {

  if ( window.location.href.search("#") > window.location.href.search("[\/][^\/]*$")) {
    window.location = window.location.href.substr (0, window.location.href.search("#"));
  }

  window.location = window.location + "#" + form.jumpDay.options[form.jumpDay.selectedIndex].value + "_" + form.jumpMonth.options[form.jumpMonth.selectedIndex].value + "_" + form.jumpYear.value;
}*/

//Sets start import hour in given toField
function setSelectedImportCell(cell,toField){
    cellName= cell.name;
    //Find hour, based on cell name
    //Hour is in (), e.g timeValue(3)
    startPos=cellName.indexOf("(")+1;
    endPos=cellName.indexOf(")");
    hour= cellName.substring(startPos,endPos);
    //set hour in toField
    document.getElementById(toField).value=hour;
}

//Gets clipboard content (text), and place it in given document element
//todo implement for other browsers than IE
function getFromClipboard(toField){
     //if IE

     if (window.clipboardData){
           var content = clipboardData.getData("Text");
           if (content!=null) {
                document.getElementById(toField).value=content;
           }

        //if netscape
        /*else if (window.netscape){

        		try{
        		var clip = Components.classes["@mozilla.org/widget/clipboard;1"].
                 getService(Components.interfaces.nsIClipboard);
                if (!clip) return false;

                var trans = Components.classes["@mozilla.org/widget/transferable;1"].
                              createInstance(Components.interfaces.nsITransferable);
                if (!trans) return false;
                trans.addDataFlavor("text/unicode");

                clip.getData(trans,clip.kGlobalClipboard);

                var str = new Object();
                var strLength = new Object();

                trans.getTransferData("text/unicode",str,strLength);
                if (str) str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
                if (str){
                    pastetext = str.data.substring(0,strLength.value / 2);
                    document.getElementById("importTimeValues").value=pastetext;
                }
                } catch (e) {
                    alert('exception '+e.message);
                }*/


        	}





}

//Submits form and closes window
function submitAndCloseWindow(form){

    selectAllDestList();
   // form.submit();
   // window.opener.location.reload(true);
    window.close();

}


 //Returns true only if char codes is number or letters
        function KeyCheckUpperCaseOrNumber(myfield,e)
        {
        	var keycode;
        	if (window.event) keycode = window.event.keyCode;
        	else if (e) keycode = e.which;
        	else return true;

        	if (((keycode>96) && (keycode<123))||((keycode>47) && (keycode<58) )  || ((keycode>64) && (keycode<91) )) { return true; }
        	else return false;
        }

        //Returns true only if element with given id exsist in document
        function isElementID(id){


            if (document.getElementById(id)==null){
                return false;
            }
            return true;
        }

        var beginCell = "";
        var endCell = "";

        //Sets sheet bounds
        function setBoundText(bound,region) {
            //returns if given cell(bound does not exist)
            if(!isElementID(bound.toUpperCase())){

                var temp=bound.substring(bound.length-1);

               if (!isNaN(temp)){
                if(bound.length>0){
                    document.getElementById(region).value=bound.substring(0,bound.length-1);
                }
               }
               return;
            }
            document.getElementById("regionBegin").value=document.getElementById("regionBegin").value.toUpperCase();
            document.getElementById("regionEnd").value=document.getElementById("regionEnd").value.toUpperCase();
            if ((document.getElementById("regionEnd").value!="")&&(!isLegal(document.getElementById("regionBegin").value,document.getElementById("regionEnd").value,true))){
                    //Illegal selections
                    //Sets blank value for regions
                    document.getElementById("regionEnd").value="";
                    document.getElementById("regionBegin").value="";

                   //Erases earlier selections
                   if(endCell!=""){
                    changeColor(beginCell,endCell,0);
                   }else{
                    document.getElementById(beginCell).style.background='#FFFFFF'
                   }
                    beginCell = "";
                    endCell = "";
                    document.getElementById("regionBegin").focus();
                    return;
            }
            if(beginCell!=""&endCell!=""){
                //Erases earlier selections
                changeColor(beginCell,endCell,0);
            }
            if(beginCell!=""){
                //Erases earlier selections
                document.getElementById(beginCell).style.background='#FFFFFF'
            }
            if(endCell!=""){
                //Erases earlier selections
                document.getElementById(endCell).style.background='#FFFFFF'
            }

            if (document.getElementById("regionEnd").value == "") {
                //Marks start cell
                document.getElementById(document.getElementById("regionBegin").value).style.background='#d9d9d9'
            } else {
                var beginRow=findRow(document.getElementById("regionBegin").value);
                var endRow=findRow(document.getElementById("regionEnd").value);
                var beginCol=findCol(document.getElementById("regionBegin").value);
                var endCol=findCol(document.getElementById("regionEnd").value);

                if(((beginRow>endRow)&(region=="regionBegin"))|(beginCol>endCol)){
                    //Swaps start and end cell
                    var temp=document.getElementById("regionBegin").value;
                    document.getElementById("regionBegin").value = document.getElementById("regionEnd").value;
                    document.getElementById("regionEnd").value = temp;
                    document.getElementById("regionBegin").focus();

                }
                //Marks selections
                changeColor(document.getElementById("regionBegin").value,document.getElementById("regionEnd").value,1);
                boundType = "regionBegin";
             }
             endCell = document.getElementById("regionEnd").value;
             beginCell = document.getElementById("regionBegin").value;


        }
       //returns true if cell is a legal selection
        function isLegal (beginCell,endCell,editText){
            var beginCol=findCol(beginCell);
            var endCol=findCol(endCell);
            var beginRow=findRow(beginCell);
            var endRow=findRow(endCell);
            if (editText&(beginCol!=endCol)&(beginCell.length>endCell.length)){
                return true;
            }
            if((beginCol!=endCol)&(endRow!=beginRow)){
                return false;
            }else{
                return true;
            }
        }
        //Sets sheet bounds
        function setBound(bound) {
            var boundType = "regionBegin";

            bound=bound.toUpperCase();
            if (document.getElementById("regionBegin").value!=""&document.getElementById("regionEnd").value==""){
                boundType = "regionEnd";

                if (!isLegal(beginCell,bound,false)){
                    return;
                }
            }

            endCell = document.getElementById("regionEnd").value;
            beginCell = document.getElementById("regionBegin").value;
            document.getElementById(boundType).value = bound;
            if (boundType == "regionBegin") {
               if (endCell!=""){
                //Erases earlier selections
                changeColor(beginCell,endCell,0);
                document.getElementById(beginCell).style.background='#FFFFFF'
               }
               //Marks start cell
               document.getElementById(bound).style.background='#d9d9d9'
               boundType = "regionEnd";
               beginCell = bound;
               document.getElementById("regionEnd").value = '';
            } else {
                var beginRow=findRow(beginCell);
                var endRow=findRow(bound);

                var beginCol=findCol(beginCell);
                var endCol=findCol(bound);
                if((beginRow>endRow)|(beginCol>endCol)){
                    //Swaps start and end cell
                    var temp=document.getElementById("regionBegin").value;
                    document.getElementById("regionBegin").value = document.getElementById("regionEnd").value;
                    document.getElementById("regionEnd").value = temp;
                    endCell=beginCell;
                    beginCell=bound;
                    document.getElementById(beginCell).style.background='#d9d9d9'
               }else{
                    endCell = bound;
               }
               //Marks selections
               changeColor(beginCell,endCell,1);
               boundType = "regionBegin";
             }

            }


	// Sets the bound type to "regionBegin" if isBegin is a non-zero value.
	function setBoundTypeBegin(isBegin) {
	    if (isBegin == 0) {
	        boundType = "regionEnd";
            } else {
    	    boundType = "regionBegin";
	    }
	}
    //Finds first char positon of a number in a string
	function findFirstNumberPositiontInString(cell){
	    var code;
        for(i = 0; i < cell.length; i++) {
            code=cell.charCodeAt(i);
            if ((code>47) && (code<58) ) {
                return i;
            }
        }

	}
	//finds row in cell(letters before number in string)
    function findRow(cell){
       var s=findFirstNumberPositiontInString(cell);
       return parseInt(cell.substring(s));
    }
    //finds colum in cell(numbers after letter(s) in string)
    function findCol(cell){
       var s=findFirstNumberPositiontInString(cell);
       return cell.substring(0,s);
    }
    //Marks selections if select=1 in sheet given start og end cell, or unmarks if select=0
    function changeColor(beginCell,endCell,select) {
        var beginCol=findCol(beginCell);
        var endCol=findCol(endCell);
        var beginRow=findRow(beginCell);
        var endRow=findRow(endCell);

        if(beginCol>endCol){
                var temp =beginCol;
                beginCol=endCol;
                endCol=temp;
             }

            var collone=beginCol.charCodeAt(0);
            var row= beginRow;
            var col= beginCol;

            while (endCol>=col){
                row= beginRow;

                while (endRow>=row){
                    if (select==1){
                        document.getElementById(col+row).style.background='#d9d9d9'
                   }else{
                        document.getElementById(col+row).style.background='#FFFFFF'
                   }
                   row++;
                }
                collone++;
                col=String.fromCharCode(collone);
            }

    }

function hideUnselected() {

   if ((document.getElementById('intervalTypePeriod')!=null)&&document.getElementById('intervalTypePeriod').checked) {
      if (document.getElementById('intervalPeriodFields')!=null){
        document.getElementById('intervalPeriodFields').style.display = "block";
      }
      if (document.getElementById('intervalWeeksFields')!=null){
        document.getElementById('intervalWeeksFields').style.display = "none";
      }
      if (document.getElementById('intervalMonthFields')!=null){
        document.getElementById('intervalMonthFields').style.display = "none";
      }
      if (document.getElementById('intervalYearFields')!=null){
        document.getElementById('intervalYearFields').style.display = "none";
      }
   } else if (document.getElementById('intervalTypeWeeks').checked) {
      if (document.getElementById('intervalPeriodFields')!=null){
        document.getElementById('intervalPeriodFields').style.display = "none";
      }
      if (document.getElementById('intervalWeeksFields')!=null){
        document.getElementById('intervalWeeksFields').style.display = "block";
      }
      if (document.getElementById('intervalMonthFields')!=null){
        document.getElementById('intervalMonthFields').style.display = "none";
      }
      if (document.getElementById('intervalYearFields')!=null){
        document.getElementById('intervalYearFields').style.display = "none";
      }
   } else if ((document.getElementById('intervalTypeMonth')!=null)&&document.getElementById('intervalTypeMonth').checked) {
      if (document.getElementById('intervalPeriodFields')!=null){
        document.getElementById('intervalPeriodFields').style.display = "none";
      }
      if (document.getElementById('intervalWeeksFields')!=null){
        document.getElementById('intervalWeeksFields').style.display = "none";
      }
      if (document.getElementById('intervalMonthFields')!=null){
        document.getElementById('intervalMonthFields').style.display = "block";
      }
      if (document.getElementById('intervalYearFields')!=null){
        document.getElementById('intervalYearFields').style.display = "none";
      }
   } else if ((document.getElementById('intervalTypeYear')!=null)&&document.getElementById('intervalTypeYear').checked) {
      if (document.getElementById('intervalPeriodFields')!=null){
        document.getElementById('intervalPeriodFields').style.display = "none";
      }
      if (document.getElementById('intervalWeeksFields')!=null){
        document.getElementById('intervalWeeksFields').style.display = "none";
      }
      if (document.getElementById('intervalMonthFields')!=null){
        document.getElementById('intervalMonthFields').style.display = "none";
      }
      if (document.getElementById('intervalYearFields')!=null){
        document.getElementById('intervalYearFields').style.display = "block";
      }

  }
}

function hideUnselected2() {


       if ((document.getElementById('viewTypeTimeseries')!=null)&&document.getElementById('viewTypeTimeseries').checked) {
          if (document.getElementById('selectedTimeSerieIds')!=null){
            document.getElementById('selectedTimeSerieIds').style.display = "block";
          }
          if (document.getElementById('timeseriesQuickSearchFields')!=null){
            document.getElementById('timeseriesQuickSearchFields').style.display = "block";
          }
          if (document.getElementById('selectedReportsIds')!=null){
            document.getElementById('selectedReportsIds').style.display = "none";
          }

       } else if ((document.getElementById('viewTypeReport')!=null)&&document.getElementById('viewTypeReport').checked) {
          if (document.getElementById('selectedTimeSerieIds')!=null){
            document.getElementById('selectedTimeSerieIds').style.display = "none";
          }
          if (document.getElementById('timeseriesQuickSearchFields')!=null){
            document.getElementById('timeseriesQuickSearchFields').style.display = "none";
          }
          if (document.getElementById('selectedReportsIds')!=null){
            document.getElementById('selectedReportsIds').style.display = "block";
          }
      }
    
}


function openCalendar (field) {
   calendarWindow = window.open("kalendar.php?field="+field, "calendar", "toolbar=no,scrollbars=no,location=no,resizable=no,status=no,directories=no,copyhistory=no,width=196,height=206");
}

function closeCalendar () {
   if (calendarWindow != null) {
      calendarWindow.close();
   }
}

function insertDate (field, date) {
   openingWindow = window.opener;
   openingWindow.document.getElementById(field).value = date;
   window.close ();
}

function showItem (item) {
   document.getElementById(item).style.display = "block";
}

function hideItem (item) {
   document.getElementById(item).style.display = "none";
}

function switchDisplayTable (item, switcher) {
   if (document.getElementById(item).style.display == "none") {
      if (navigator.appName.indexOf("Microsoft")!=-1) {
         document.getElementById(item).style.display = "block";
      } else {
         document.getElementById(item).style.display = "table-row-group";
      }
      switcher.style.backgroundImage = "url('images/arrow_down.png')";
   } else {
      document.getElementById(item).style.display = "none";
      switcher.style.backgroundImage = "url('images/arrow_right.png')";
   }
}

function hideInfo() {
   switchDisplayTable ('timeValuesPropertiesContent', document.getElementById("timeValuesPropertiesCaption"));
   switchDisplayTable ('timeSeriesInfoContent', document.getElementById("timeSeriesInfoCaption"));
}

//List chooser

function SelObj(selname,textname,str) {
   this.selname = selname;
   this.textname = textname;
   this.select_str = str || '';
   this.selectArr = new Array();
   this.initialize = initialize;
   this.bldInitial = bldInitial;
   this.bldUpdate = bldUpdate;
   this.initialized = false;
}

function initialize() {
   if (this.select_str =='') {
      if (document.getElementById(this.selname)!=null){
          for(i = 0; i < document.getElementById(this.selname).options.length; i++) {
             this.selectArr[i] = document.getElementById(this.selname).options[i];

             this.select_str += document.getElementById(this.selname).options[i].value+":"+
             document.getElementById(this.selname).options[i].text+",";
          }
      }
   } else {
      var tempArr = this.select_str.split(',');
      for(var i=0;i<tempArr.length;i++) {
         var prop = tempArr[i].split(':');
         this.selectArr[i] = new Option(prop[1],prop[0]);
      }
   }
   return;
}

function bldInitial() {
   this.initialize();
   for(i = 0; i < this.selectArr.length; i++)
      document.getElementById(this.selname).options[i] = this.selectArr[i];
   if (this.initialized) {
      document.getElementById(this.selname).options.length = --this.selectArr.length;
   } else {
      if(document.getElementById(this.selname)!=null){
        document.getElementById(this.selname).options.length = this.selectArr.length;
      }
   }
   return;
}

function updateList() {


   document.getElementById('timeseriesQuickSearch').value='';
   selectList.bldUpdate();
   return;
}

function bldUpdate() {
   var selList =new Array();
   var selectedCount=0;
   if (document.getElementById(this.selname)!=null){
          for(i = 0; i < document.getElementById(this.selname).options.length; i++) {
            if (document.getElementById(this.selname).options[i].selected){
                selList[selectedCount++] = document.getElementById(this.selname).options[i].text;
            }

          }
      }
   oldList =document.forms[0].selectedTimeSerieIds;
   var str = document.getElementById(this.textname).value.replace('^\\s*','');
   if(str == '') {
      this.initialized = true;
      this.bldInitial();
      var j = 0;
      for(i = 0; i < this.selectArr.length; i++) {
      //if(pattern1.test(this.selectArr[i].text)) {
        document.getElementById(this.selname).options[j++] = this.selectArr[i];
        for(k = 0; k < selList.length; k++) {
            if (document.getElementById(this.selname).options[j-1].text==selList[k]){
                document.getElementById(this.selname).options[j-1].selected = true;
            }
        }
      //}
      document.getElementById(this.selname).options.length = j;
    }



      return;
   }

   this.initialize();
   var j = 0;
   pattern1 = new RegExp("^"+str,"i");


   for(i = 0; i < this.selectArr.length; i++) {
      if(pattern1.test(this.selectArr[i].text)) {
        document.getElementById(this.selname).options[j++] = this.selectArr[i];
        for(k = 0; k < selList.length; k++) {
            if (document.getElementById(this.selname).options[j-1].text==selList[k]){
                document.getElementById(this.selname).options[j-1].selected = true;
            }
        }
      }
      document.getElementById(this.selname).options.length = j;
    }
}
function setUp() {
   selectList = new SelObj('selectedTimeSerieIds','timeseriesQuickSearch');
   // menuform is the name of the form you use
   // itemlist is the name of the select pulldown menu you use
   // entry is the name of text box you use for typing in
   selectList.bldInitial();
   if (document.getElementById(selectList.textname)!= null&& document.getElementById(selectList.textname).value!=""){
        selectList.bldUpdate();
   }

}

//List chooser end

// Presents a larger window in which the user can select time series
//open window
function newWindow(url,width,height) {
	//var features = "toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=0, copyhistory=1, resizable=1, width=620, height=650;"
	var features = "toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=0, copyhistory=1, resizable=1, width="+width+", height="+height+";"
	var popupWindow;
	popupWindow=window.open(url, "selectTsWindow", features);
//	popupWindow=window.open("/emp/timeseries/components/jsp/selectTsPopup.jsp", "selectTsWindow", features);
	popupWindow.focus();
}

// Fill the avaliable item list with the items  present in parent.
function fillInitialSrcList() {
	var srcList = window.document.forms[0].srcList;
	var parentList = self.opener.window.document.forms[0].selectedTimeSerieIds;
	for (var count = srcList.options.length - 1; count >= 0; count--) {
		srcList.options[count] = null;
	}
	for(var i = 0; i < parentList .options.length; i++) {
		if (parentList .options[i] != null)
		srcList.options[i] = new Option(parentList .options[i].text,parentList .options[i].value);
   	}
}

function setUpPopup() {
   selectList = new SelObj('srcList','timeseriesQuickSearchPopup');
   // menuform is the name of the form you use
   // itemlist is the name of the select pulldown menu you use
   // entry is the name of text box you use for typing in
   selectList.bldInitial();
}
// Adds the list of selected items selected in the child
// window to its list. It is called by child window to do so.
function addToParentList(sourceList) {
	destinationList = window.document.forms[0].selectedTimeSerieIds;
	for(var count = destinationList.options.length - 1; count >= 0; count--) {
		destinationList.options[count] = null;
	}
	for(var i = 0; i < sourceList.options.length; i++) {
		if (sourceList.options[i] != null)
			destinationList.options[i] = new Option(sourceList.options[i].text, sourceList.options[i].value );
	 }
}
// Marks all the items as selected for the submit button.
function selectList(sourceList) {
	sourceList = window.document.forms[0].parentList;
	for(var i = 0; i < sourceList.options.length; i++) {
		if (sourceList.options[i] != null)
			sourceList.options[i].selected = true;
	}
	return true;
}

// Deletes the selected items of supplied list.
function deleteSelectedItemsFromList(sourceList) {
	var maxCnt = sourceList.options.length;
	for(var i = maxCnt - 1; i >= 0; i--) {
		if ((sourceList.options[i] != null) && (sourceList.options[i].selected == true)) {
			sourceList.options[i] = null;
     	}
  	}
}

function closeWindow() {
    window.close();
}

// Add the selected items in the parent by calling method of parent
function addSelectedItemsToParent() {
//	self.opener.addToParentList(window.document.forms[0].selectedTimeSerieIds);
//	window.close();
}


// Add the selected items from the source to destination list
function addSrcToDestList() {
	selectedTimeSerieIds = window.document.forms[0].selectedTimeSerieIds;
	srcList = window.document.forms[0].srcList;
	var len = selectedTimeSerieIds.length;
	for(var i = 0; i < srcList.length; i++) {
		if ((srcList.options[i] != null) && (srcList.options[i].selected)) {
			//Check if this value already exist in the selectedTimeSerieIds or not
			//if not then add it otherwise do not add it.
			var found = false;
			for(var count = 0; count < len; count++) {
				if (selectedTimeSerieIds.options[count] != null) {
					if (srcList.options[i].text == selectedTimeSerieIds.options[count].text) {
						found = true;
						break;
     	 			}
   				}
			}
			if (found != true) {
				selectedTimeSerieIds.options[len] = new Option(srcList.options[i].text,srcList.options[i].value);
				len++;
         	}
     	 }
   	}
}

// Sets all items in destination list to selected
function selectAllDestList() {
	selectedTimeSerieIds = window.document.forms[0].selectedTimeSerieIds;
	selectedTimeSerieIdsOpner = window.opener.document.forms[0].selectedTimeSerieIds;

    for(var i = 0; i < selectedTimeSerieIdsOpner.length; i++) {
            if ((selectedTimeSerieIdsOpner.options[i] != null)&(selectedTimeSerieIdsOpner.options[i].text != "")){
                selectedTimeSerieIdsOpner.options[i].selected=false;
            }
     }

	for(var i = 0; i < selectedTimeSerieIds.length; i++) {
	    for(var j = 0; j < selectedTimeSerieIdsOpner.length; j++) {
            if ((selectedTimeSerieIds.options[i] != null)&(selectedTimeSerieIds.options[i].text != "")&(selectedTimeSerieIds.options[i].text==selectedTimeSerieIdsOpner.options[j].text)){
                selectedTimeSerieIdsOpner.options[j].selected="true";
            }
        }

   	}
}

// Sets all items selected in opner list to selected in popup
function addOpnerListToDestList() {
	//selectedTimeSerieIds = window.document.forms[0].selectedTimeSerieIds;
	//selectedTimeSerieIdsOpner = window.opener.document.forms[0].selectedTimeSerieIds;

	selectedTimeSerieIds = window.document.forms[0].selectedTimeSerieIds;
	srcList = window.opener.document.forms[0].selectedTimeSerieIds;
	var len = selectedTimeSerieIds.length;
	for(var i = 0; i < srcList.length; i++) {
		if ((srcList.options[i] != null) && (srcList.options[i].selected)) {
			//Check if this value already exist in the selectedTimeSerieIds or not
			//if not then add it otherwise do not add it.
			var found = false;
			for(var count = 0; count < len; count++) {
				if (selectedTimeSerieIds.options[count] != null) {
					if (srcList.options[i].text == selectedTimeSerieIds.options[count].text) {
						found = true;
						break;
     	 			}
   				}
			}
			if (found != true) {
				selectedTimeSerieIds.options[len] = new Option(srcList.options[i].text,srcList.options[i].value);
				len++;
         	}
     	 }
   	}
}

// Deletes from the destination list.
function deleteFromDestList() {
	var selectedTimeSerieIds  = window.document.forms[0].selectedTimeSerieIds;
	var len = selectedTimeSerieIds.options.length;
	for(var i = (len-1); i >= 0; i--) {
		if ((selectedTimeSerieIds.options[i] != null) && (selectedTimeSerieIds.options[i].selected == true)) {
			selectedTimeSerieIds.options[i] = null;
		 }
	  }
}
// End -->
//  End selectTs popup

function show(object, timeseries) {
        document.forms[1].action.value=object.options[object.selectedIndex].value;

        document.forms[1].timeSeriesIndex.value=timeseries;
        document.forms[1].submit();
   }