﻿// JScript File

/*sértilvik fyrir operabrowser*/
function OpenWindow(url)
{
    window.open(url);
    return false;
}
/*Passar að multiline textox fari yfir maxlength*/
function TextBoxMaxLength(text,length, messages)
{
	var maxlength = new Number(length); // Change number to your max length.
	if (text.value.length > maxlength)
	{
		//text.value = text.value.substring(0,maxlength);
		alert(messages);
	}
}
function CancelRequest(changedFields, message, uri)
{
   // var cangedTextBox = GetElement(changedFields);
//   var changed = !CheckSave(changedFields);
//   alert(changed);
    if (!CheckSave(changedFields) || confirm(message))
    {
        window.location = uri;
        /*'../View/View.aspx?viewId=63'
        alert('../View/View.aspx?viewId=63');
        history.go('../View/View.aspx?viewId=63');*/
    }
    return false;
}
//fjarlægir allar valdar færslur í multipick
function removeOption(textboxid, controlId, deleteid, originalid, checkboxid)
{
  var elSel = document.getElementById(controlId);  
  var theTextbox = GetElement(textboxid); 
  var theDeleteButton = GetElement(deleteid);
  theTextbox.value = '';
  var i;
  //loopa alla sem eru valdir
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) 
    {
      elSel.remove(i);
    }
    else
    {
        if(theTextbox.value == '')
        {
            theTextbox.value =  elSel.options[i].value;
        }
        else
        {
            theTextbox.value = theTextbox.value + ';' + elSel.options[i].value;
        }
    }
  }
  
  //fela delete button
   if(elSel.length > 0)
    {
        theDeleteButton.style.visibility = 'visible';
    }
    else
    {
        theDeleteButton.style.visibility = 'hidden';   
    }
  
  //merkja við hvort gildið er það sama og upprunalega
  ControlChangedListBox(textboxid,originalid,checkboxid);
}

//Bætir við í listbox fyrir multipick
function addOption(textboxid, listboxid, deleteid, theText)
{          
    var theTextbox = GetElement(textboxid);
    if(theText != '')
    {
        if(!itemExists(listboxid, theText))
        {
            if(theTextbox.value == '')//sleppum við fyrsta ;
            {
                theTextbox.value = theText; 
            }
            else
            {
                theTextbox.value = theTextbox.value + ';' + theText; 
            }
            
	        theText = RemoveRequestString(theText);
	        
            addOptionToListBox(listboxid, theText, deleteid);
        }
    }
}

/*fjarlægir allt innan [ ]*/
function RemoveRequestString(theText)
{
    //taka opna spjald skilyrði
    var start = theText.indexOf('[',0);            
    var end = theText.indexOf(']',0);   
    
    if(start != -1 && end != -1)
    {
        end = end + 1;
        theText = theText.substring(0,start) + theText.substring(end, theText.length);
        //trimma ' '  
        theText = theText.replace(/^\s*|\s*$/g,"");      
    }
    
    return theText
}

/*skilar öllu innan [ ]*/
function ExtracteRequestString(theText)
{
    //taka opna spjald skilyrði
    var start = theText.indexOf('[',0);            
    var end = theText.indexOf(']',0);   
    
    if(start != -1 && end != -1)
    {
        theText = theText.substring(start+1,end);
        //trimma ' '  
        theText = theText.replace(/^\s*|\s*$/g,"");      
    }
    
    return theText
}

//athugar hvort item er til í listboxi
function itemExists(listboxid, theText)
{
    var theListbox = GetElement(listboxid);
    var i;
    
     for (i = theListbox.length - 1; i>=0; i--) 
     {
       if (theListbox.options[i].value == theText)    
       {
            return true;
       }
     }
     
     return false;    
}

//Bætir við í listbox fyrir pickup
function addOptionTextbox(textboxid, listboxid, deleteid, theText)
{          
    var theTextbox = GetElement(textboxid);
    var theListbox = GetElement(listboxid);
    theTextbox.value = theText; //á að innihalda [ ]
    theListbox.innerHTML = '';
    
	theText = RemoveRequestString(theText);
	
    var newOpt = new Option(theText, theText);
    var selLength = theListbox.length;
    theListbox.options[selLength] = newOpt;
}

//Bætir við í listbox fyrir multipicker
function addOptionToListBox(listboxid, theText, deleteid)
{         
    if(theText != '')
    {
        var theListbox = GetElement(listboxid);
        var theDeleteButton = GetElement(deleteid);
        var newOpt = new Option(theText, theText);
        var selLength = theListbox.length;
        theListbox.options[selLength] = newOpt;
    }
    
    if(theListbox.length > 0)
    {
        theDeleteButton.style.visibility = 'visible';
    }
    else
    {
        theDeleteButton.style.visibility = 'hidden';   
    }
}

//Skilar gildi úr textboxi
function getValueFromTextbox(textboxid)
{
    return GetElement(textboxid).value; 
}

//Breytir urli á picker stýringu til að geta opnað spjald
function ChangeHrefPick(controlId, url, text)
{
    
    var control = GetElement(controlId);
   
    if(text == "")
    {
        control.style.visibility = 'hidden';
    }
    else
    {        
        control.style.visibility = 'visible';
    }   
    
    control.href = url + text;    
}

//Breytir urli á stýringu
function ChangeHref(id, sel, url)
{
//alert(id +','+sel+','+url);
    var control = GetElement(sel);
    var selControl = GetElement(id);
    var index = selControl.selectedIndex;
    if (index != -1)
    {
        var selectedValue = selControl.options[index].value;
        selectedValue = ExtracteRequestString(selectedValue);
        //selectedValue = selectedValue.replace('[', '').replace(']', '')
        if(selectedValue == "")
        {
            control.style.visibility = 'hidden';
        }
        else
        {
            control.style.visibility = 'visible';
        }
        //alert(control.style.visibility);
        
        control.href = url + selectedValue;
    }
    
}

//Sýnir eða felur stýringu
function ShowHide(controlId)
{
    var control = GetElement(controlId);
    if(control.style.display == 'none')
    {   
        control.style.display = 'inline';
    }
    else
    {
        control.style.display = 'none'; 
    }
}

//Setur undirflokk í textbox til að geyma
function SetSubCategory(dropdownlist, textbox)
{
    var theSel = GetElement(dropdownlist);
    var theText = GetElement(textbox);
    theText.value = theSel.value;
}

//Birtir confirm glugga ef stöðubreyting krefst þess
function ConfirmStateChange(messages, stateControlId)
{
    var messages_array = messages.split("@");
    for(i = 0; i < messages_array.length; i++)
    {
        if(messages_array[i] != '')
        {
            var msg_arr = messages_array[i].split(";");
            var control = GetElement(stateControlId);
            var index = control.selectedIndex;
            if (index != -1) 
            {
                var selectedValue = control.options[index].value;               
                if(msg_arr[0] == selectedValue)
                {
                    messages = msg_arr[1];
                    return confirm(messages);
                }
            }
        }
    }
    return true;
}

//Setur upp calendar stýringu án tíma
function SetUpCalendarNoTime(calendarid, buttonid)
{
    Calendar.setup({
    inputField		:   calendarid,
    ifFormat		:   "%d.%m.%Y",
    button			:   buttonid,
    align			:   "Br",
    singleClick		:   true,
    firstDay		:	1,
    step			:	1
    })
}
/**
 * Hides or shows a control
 * @public
 * @param controlId id of control to show or hide
 */
ShowHide = function (controlId){
  var control = GetElement(controlId);
  if(control.style.display == 'none'){   
    control.style.display = '';
  }
  else{
    control.style.display = 'none'; 
  }
}
//Setur upp calendar stýringu með tíma
function SetupCalendarFlat(calendarid,inputfieldid)
{
Calendar.setup(
    {
      flat         : calendarid, // ID of the parent element
      flatCallback : dateChanged,           // our callback function
    ifFormat		:   "%d.%m.%Y %H:%M",
    align			:   "Br",
    singleClick		:   true,
    firstDay		:	1,
    step			:	1,
    showsTime       :   true,
    timeFormat      :   24,
    showOthers      :   true
    },inputfieldid)

}
//Setur upp calendar stýringu með tíma
function SetupCalendarFlatNoTime(calendarid,inputfieldid)
{
Calendar.setup(
    {
      flat         : calendarid, // ID of the parent element
      flatCallback : dateChanged,           // our callback function
       ifFormat		:   "%d.%m.%Y",
      align			:   "Br",
       singleClick		:   true,
    firstDay		:	1,
    step			:	1,
    showOthers      :   true
    },inputfieldid)

}

//Setur upp calendar stýringu með tíma
function SetUpCalendar(calendarid, buttonid)
{
    Calendar.setup({
    inputField		:   calendarid,
    ifFormat		:   "%d.%m.%Y %H:%M",
    button			:   buttonid,
    align			:   "Br",
    singleClick		:   true,
    firstDay		:	1,
    step			:	1,
    showsTime       :   true,
    timeFormat      :   24
    })
}

 function dateChanged(calendar,date) {
    // Beware that this function is called even if the end-user only
    // changed the month/year.  In order to determine if a date was
    // clicked you can use the dateClicked property of the calendar:
    if (calendar.dateClicked) {
    GetElement(calendar.inputid).value = date;
    ShowHide('calendar-container'+calendar.inputid);
    //calendar.callCloseHandler(); 
//      // OK, a date was clicked, redirect to /yyyy/mm/dd/index.php
//      var y = calendar.date.getFullYear();
//      var m = calendar.date.getMonth();     // integer, 0..11
//      var d = calendar.date.getDate();      // integer, 1..31
//      // redirect...
//      window.location = "/" + y + "/" + m + "/" + d + "/index.php";
    }
  };


//Fall sem hendir út stöfum sem eru ekki tölustafir
function noCharacters(e)
{
	//Target stýringin sem eventinn kom frá
	var targ;
	//Keykode sem kom inn
	var code;
	//Var control haldið inni?
	var ctrl = false;
	
	if (!e)
	{
		//IE tekur ekki við eventum sem arguments
		//Náum því í eventinn úr global breytunni event
		var e = window.event;
	}
	
	//Náum í stýringuna sem orsakaði eventinn, srcElement er IE only
	if (e.target)
	{
		targ = e.target;
	}
	else if (e.srcElement) 
	{
		targ = e.srcElement;
	}
	if (targ.nodeType == 3) // defeat Safari bug
	{
		targ = targ.parentNode;
	}

	//Náum í hvaða takka var ýtt á which er Netscape only
	if (e.keyCode) 
	{//Erum með IE eða Opera
		code = e.keyCode;
		ctrl = e.ctrlKey;
	}
	else if (e.which) 
	{//Erum með Netscape eða Mozilla
		code = e.which;
		if(e.CONTROL_MASK)
		{
			ctrl = true;
		}
	}

	if (code < 48 || code > 57)
	{//Ekki er smellt á tölutakka 99 = c(copy) 118=v(paste) 8 = backspace 46=delete 37=leftArrow 39 = rightArrow
		if(!((ctrl && code == 99) || (ctrl && code == 118) || code == 8 || code == 46 || code == 45 || code == 44 || code == 37 ))
		{//Ekki verið að kópera eða peista
			if(e.preventDefault)
			{//Netscape
				e.preventDefault();
			}
			else
			{//IE
				e.returnValue = false;
			}
		}
	}
}

// Tekur inn einn staf, skilar true ef um tölustaf er að ræða annars false 
function isDigit(num) 
{
	if (num.length>1)
	{
		return false;
	}
	var string="1234567890";
	if (string.indexOf(num)!=-1)
	{
		return true;
	}
	return false;
}

//setur send stöðuna þegar ýtt er á send
function setState(statecontrol, state)
{
//alert(state)
    var stateCtl = GetElement(statecontrol);
    //stateCtl.selectedvalue = state;
    //stateCtl.selectedvalue = state
    //if (stateCtl.selectedvalue !=  )
    //{
        for(i = 0; i < stateCtl.length; i++)
        {          
            var newOpt = stateCtl.options[i];
            if(newOpt.value = state)
            {
               // stateCtl.options[i].selected = true;
               stateCtl.selectedIndex = i; 
            }
        }    
    //}
}

/*addað 27.07.06*/
//geymir hvort textbox svið hefur breyst
function ControlChangedTextBox(changedControlId, originalControlId, checkboxId)
{      

  var changedTextbox = GetElement(changedControlId);
  var orginalTextbox = GetElement(originalControlId);
  var checkbox = GetElement(checkboxId);
  if(changedTextbox == null || orginalTextbox == null || checkbox == null)
  {
  }
  else
  {            
           // alert(changedControlId);
        if(changedControlId.indexOf('S1F9',0) != -1) 
        {
            for(var i = 0; i < changedTextbox.value.length; i++)
            {
                //alert('fyrri=' +changedTextbox.value.charAt(i)+'#');
               // alert('seinni=' +orginalTextbox.value.charAt(i)+'#');
                if(changedTextbox.value.charAt(i) != orginalTextbox.value.charAt(i))
                {
                   // alert(changedTextbox.value.charAt(i) + ' at ' + i + ' is ' +orginalTextbox.value.charAt(i));
                }
            }
        }
        
      if(changedTextbox.value == orginalTextbox.value)
      {
        checkbox.checked = false;      
      }
      else
      {
        checkbox.checked = true; 
      }
  }
}
//geymir hvort select svið hefur breyst
function ControlChangedDropDownList(changedControlId, originalControlId, checkboxId)
{      
  var changedDropDownList = GetElement(changedControlId);
  var orginalTextbox = GetElement(originalControlId);
  var checkbox = GetElement(checkboxId);
  
  if(changedDropDownList == null || orginalTextbox == null || checkbox == null)
  {
  }
  else
  {  
      var selectedValue = '';
      var index = changedDropDownList.selectedIndex;
      if (index != -1) 
      {
          if(changedControlId.indexOf('DropDownListMainCategory') > -1)//ef þetta er yfirflokkur
          {
                selectedValue = changedDropDownList.options[index].text;          
          }
          else
          {
                selectedValue = changedDropDownList.options[index].value;
          }    
      }
      
       
      
      if(selectedValue == orginalTextbox.value)
      {
        checkbox.checked = false;      
      }
      else
      {
        checkbox.checked = true; 
      }
      
      //sértilfelli fyrir yfir og undirflokka
      if(changedControlId.indexOf('DropDownListMainCategory') > -1)//ef þetta er yfirflokkur
      {
        ControlChangedDropDownList(changedControlId.replace('Main', 'Sub'), originalControlId.replace('Main', 'Sub'), checkboxId.replace('Main', 'Sub'));
        
      }
      
  }
}

//sækir og birtir undirflokka
function GetSubCategory(controlId, textboxid)      
{
    var dropDownList = GetElement(controlId);
    var dropDownListSub = GetElement(controlId.replace('Main', 'Sub'));
  
    var index = dropDownList.selectedIndex;
    if (index > 0) 
    {
        var selectedValue = dropDownList.options[index].value;
        //setur subcatecory í textbox
        PreserveSubCategory(selectedValue, textboxid);
        
        var theTextbox_array = selectedValue.split(';');
        dropDownListSub.innerHTML = '';//hreinsar listboxið
        for(i = 0; i < theTextbox_array.length; i++)
        {
            if(i > 0)//fyrsta gildið er yfirflokkurinn
            {
                var newOpt = new Option(theTextbox_array[i], theTextbox_array[i]);
                var selLength = dropDownListSub.length;
                dropDownListSub.options[selLength] = newOpt;
            }
        }        
    }    
    SetSubCategory(controlId.replace('Main', 'Sub'),controlId.replace('Main', 'Sub').replace('DropDownList', 'TextBox') + 'StateView');
}

//geymir undirflokka í textboxi
function PreserveSubCategory(subcategories, controlId)
{
    var textbox = GetElement(controlId);
    textbox.value = subcategories;
}

//Setur picker gildi í textbox þegar hakað er í picker
function SetPickerValue(control, textboxControl, id)
{

    var checkcontrol = GetElement(control);
    var textcontrol = GetElement(textboxControl);
    
    textcontrol.value = textcontrol.value.replace(id, '');    
    
    if(checkcontrol.checked == true)
    {
        textcontrol.value = textcontrol.value + id
    }
}

//geymir hvort listbox svið hefur breyst
function ControlChangedListBox(changedControlId, originalControlId, checkboxId)
{      
  var changedTextbox = GetElement(changedControlId);
  var orginalTextbox = GetElement(originalControlId);
  var checkbox = GetElement(checkboxId);
  
  if(changedTextbox == null || orginalTextbox == null || checkbox == null)
  {
  
  }
  else
  {  
      if(ArraysAreEqual(changedTextbox.value.split(';'), orginalTextbox.value.split(';')) && 
      ArraysAreEqual(orginalTextbox.value.split(';'), changedTextbox.value.split(';')))
      {
        checkbox.checked = false;      
      }
      else
      {
        checkbox.checked = true; 
      }
  }
}

//geymir hvort checkbox svið hefur breyst
function ControlChangedCheckBox(changedControlId, originalControlId, checkboxId)
{      
   
  var changedTextbox = GetElement(changedControlId);
  var orginalTextbox = GetElement(originalControlId);
  var checkbox = GetElement(checkboxId);
  
  if(changedTextbox == null || orginalTextbox == null || checkbox == null)
  {
  }
  else
  {
      
      if((orginalTextbox.value.length > 0 && changedTextbox.checked) || (orginalTextbox.value == '' && !changedTextbox.checked))
      {
        checkbox.checked = false;      
      }
      else
      {
        checkbox.checked = true; 
      }
  }
}

//athugar hvort tvö array eru eins
function ArraysAreEqual(array1,array2)
{
    var found;
    for(i = 0; i < array2.length; i++)
    {
        found = false;
        for(j = 0; j < array1.length; j++)
        {
            if(array2[i] == array1[j])
            {
                found = true;                    
            }
        }        
        if(!found)
        {
            return false;
        }
    }  
    return true;
}

//Athugar hvort það séu óvistuð gögn
function ConfirmDirtySave(control, text)
{
    if(CheckSave(control))
    {
        return confirm(text);
    }
}      

//Athugar hvort eitthvað checkbox er checkað
function CheckSave(control)
{
    var checkBoxArray = GetElement(control).value.split(';');
    var checkBox = null;
    var hasUnsavedData = false;
    for(i = 0; i < checkBoxArray.length; i++)
    {
        if(checkBoxArray[i] != '')
        {        
            if(GetElement(checkBoxArray[i]).checked)
            {
                hasUnsavedData = true;                    
            }
        }
    }   
    return hasUnsavedData;
}

//Athugar hvort eitthvað checkbox er checkað
function LoadDirty(control, controlKeep, preload)
{
    var textboxKeep = GetElement(controlKeep);
    var checkBoxArray = GetElement(control).value.split(';');
    var checkBox = null;
    var hasUnsavedData = false;
    textboxKeep.value = '';
    for(i = 0; i < checkBoxArray.length; i++)
    {
        if(preload)
        {
            var prefix = checkBoxArray[i].substring(0,checkBoxArray[i].length - '_Check'.length);
                      
            CheckChangedFields(prefix,prefix + '_Changed',prefix + '_Check');
        }
        
        if(checkBoxArray[i] != '')
        {                    
            if(GetElement(checkBoxArray[i]).checked)
            {
                textboxKeep.value = textboxKeep.value + checkBoxArray[i] + ';';
            }
        }
    }   
    return hasUnsavedData;
}

//Athugar hvort eitthvað checkbox er checkað
function CheckChangedFields(changedControlId, originalControlId, checkboxId)
{
    if(changedControlId.indexOf('ListBox',0) != -1)
    {
        ControlChangedListBox(changedControlId, originalControlId, checkboxId);
    }
    else if(changedControlId.indexOf('CheckBox',0) != -1)
    {
        ControlChangedCheckBox(changedControlId, originalControlId, checkboxId);
    }
    else if(changedControlId.indexOf('TextBox',0) != -1)
    {
        ControlChangedTextBox(changedControlId, originalControlId, checkboxId);
    }
    else if(changedControlId.indexOf('DropDownList',0) != -1)
    {
        ControlChangedDropDownList(changedControlId, originalControlId, checkboxId);
    }

}
