/*Scripts that we use for several pages*/

function check(fYear, fMonth){
	var valid = false;
	var year = document.getElementById(fYear);
	var month = document.getElementById(fMonth);	
			
	if (isNaN(year.value)){
		alert('Året måste vara ett nummer!');
		year.focus();
	}
	else if (isNaN(month.value) || month.value > 12 || month.value < 1){
		alert('Månaden måste vara ett nummer mellan 1 och 12!');
		month.focus();
	}	
	else
		valid = true;
		
	return valid;
}

function checkOnlyYear(fYear, fMonth){
	var valid = false; 
	var year = document.getElementById(fYear);
	var month = document.getElementById(fMonth);	
			
	if (isNaN(year.value)){
		alert('Året måste vara ett nummer!');
		year.focus();
	}
	else if (month.value != "") {
		if(isNaN(month.value) || month.value > 12 || month.value < 1){
			alert('Månaden måste vara ett nummer mellan 1 och 12!');
			month.focus();
		}
		else
			valid = true;
	}	
	else
		valid = true;
		
	return valid;
}

function invalidDeleteRedirect(url) {
	var msg = "Du har inte behörighet att ta bort denna bokning.\n";
	msg += "Kontakta TV4 om Du behöver ytterligare hjälp.";
	alert(msg);
	window.location = url;
}

function bookingRedirect(url) {
	var msg = "Bokningen kunde inte tas bort/ändras.\n";
	msg += "Detta beror på att TV4 har mottagit, och därmed låst, bokningen innan du hann ta bort/ändra den.\n";
	msg += "Det innebär också att bokningen har flyttats till Ditt arkiv";
	alert(msg);
	window.location = url;
}

function go(inurl) {
	best_win = window.open(inurl,"best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
}

function goPrint(print, inurl, view) {
	if (!print) {
		if (window.location.toString().indexOf("?") > -1){
			best_win = window.open(inurl + "&view=" + view,"best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
		}
		else{
			best_win = window.open(inurl + "?view=" + view,"best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
		}
	}
	else
		window.print();
}
function goHistoryPrint(inurl) {
	if (window.location.toString().indexOf("&print=true") == -1) {
		if (window.location.toString().indexOf("?") > -1){
			best_win = window.open(inurl + "&print=true","best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
		}
		else{
			best_win = window.open(inurl + "?print=true","best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
		}
	}
	else
		window.print();
}
function goPrint2(print, inurl) {
	if (print == 0) {
		if (window.location.toString().indexOf("?") > -1){
			best_win = window.open(inurl,"best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
		}
		else{
			best_win = window.open(inurl,"best_win","toolbar=no,menubar=yes,resizable=yes,scrollbars=yes,dependent=no,screenX=50,screenY=50");
		}
	}
	else
		window.print();
}
var LOW_RES = 800;
var NORMAL_RES = 1024;
var HIGH_RES = 1280;
var VERYHIGH_RES = 1400; 
var isLocked = 0;

function getResolution() {
	if (screen.width >= VERYHIGH_RES)
		return VERYHIGH_RES;
	else if (screen.width >= HIGH_RES)
		return HIGH_RES;
	else if (screen.width >= NORMAL_RES)
		return NORMAL_RES;
	else
		return LOW_RES;
}

function getWidth(id, resolution) {
	var width = 0;
	var LEFTNAVWIDTH = 150;
	switch(id) {
		case "mainOrder":
			if (resolution == VERYHIGH_RES)
				width = VERYHIGH_RES - LEFTNAVWIDTH;
			else if (resolution == HIGH_RES)
				width = HIGH_RES - LEFTNAVWIDTH;
			else if (resolution == NORMAL_RES)
				width = NORMAL_RES - LEFTNAVWIDTH;
			else
				width = LOW_RES - LEFTNAVWIDTH;
		break;
		default:
			if (resolution == VERYHIGH_RES)
				width = VERYHIGH_RES - LEFTNAVWIDTH;
			else if (resolution == HIGH_RES)
				width = HIGH_RES - LEFTNAVWIDTH;
			else if (resolution == NORMAL_RES)
				width = NORMAL_RES - LEFTNAVWIDTH;
			else
				width = LOW_RES - LEFTNAVWIDTH;
			break;
	}
	return width;
}

function setWidth(id) {
	var mainwidth = getWidth(id, getResolution());
	document.getElementById(id).style.width = mainwidth;		
}
				
function setForm(formName){
	if (typeof document.forms[formName] == 'undefined'){
		if (document.layers){
		
			for (x=0;x<document.layers.length;x++){
				if (typeof document.layers[x].document.forms[formName] == 'object'){
					theForm=document.layers[x].document.forms[formName];
				
				}
			}
		}
	}
	else{
		theForm=document.forms[formName];
		
	}
	return theForm;
}

/* Description: this function validates a form. The first argument is the formname or form-index. After the form name
you can validatea an optional number of fields on the form. Every field to validate requires tree arguments
in correct order: 	
Field name - the name in the name-tag for the field or the element-index.
Type - "text", "date", "radio" or "number"
Message - the message the user is displayed if the validation fails for the field.	*/
function validateForm(formName){

	var theForm;
	theForm = setForm(formName);

	if (((arguments.length-1)%3) != 0){
		alert("Wrong number of arguments");
		return false;
	}

	for (var i=1; i<arguments.length; i+=3) {
      		fName = arguments[i];
		fType = arguments[i+1];
		fMessage = arguments[i+2];

		if (fType == "date"){
			if (!validateSingleDate(theForm.elements[fName].value)){
				alert(fMessage);
				theForm.elements[fName].focus();
				return(false);			
			}
		}
		else if (fType == "text")
		{
			if (!containsValue(theForm.elements[fName].value)){
				alert(fMessage);
				theForm.elements[fName].focus();
				return(false);			
			}
		}
		else if (fType == "number")
		{
			if (isNaN(theForm.elements[fName].value) | !containsValue(theForm.elements[fName].value)){
				alert(fMessage);
				theForm.elements[fName].focus();
				return(false);	
			}
		}
		else if (fType == "radio") 
		{
		   var isChecked;
		   for (var j = 0; j < theForm.elements[fName].length; j++){
				if (theForm.elements[fName][j].checked) {
					isChecked = true;
					break;
				}   
		   }
		   if (!isChecked) {
				alert(fMessage);
				theForm.elements[fName][0].focus();
				return(false);	
		   }		   
		}   		
 		else
			alert("Wrong type in argument for field");	
	
	}   

	return true;

}

function containsValue(element) {
    /* Does the element contain a value? */
    if (element == "" || element == null || element == -1 )
          return false;
    else return true;
}

function validateDate(source, arguments)
{
	/*	This function checks that the input date field is a valid date of the form yyyy-mm-dd 
		Use it with the CustomValidator!
	*/
	var datum;
	var bTrue = true;
	datum = arguments.Value;
	if (datum.length != 10)
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	if (datum.charAt(4) != "-")
		{
			bTrue = false;
			arguments.IsValid=false;   
			return;
		}
	if (datum.charAt(7) != "-")
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}

	yys = datum.substring(0,4);
	if (isNaN(yys))
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	else
		{
			yy = parseInt(yys,10);
		}

	mms = datum.substring(5,7);
	if (isNaN(mms))
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	else
		mm = parseInt(mms,10);

	dds = datum.substring(8,10);
	if (isNaN(dds))
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	else
		dd = parseInt(dds,10);

	if ((yy % 4) == 0)
		feb = 29;
	else
		feb = 28;

	max = 0;
	switch (mm){
		case 1 : max = 31;
		break;
		case 3 : max = 31;
		break;
		case 5 : max = 31;
		break;
		case 7 : max = 31;
		break;
		case 8 : max = 31;
		break;
		case 10 : max = 31;
		break;
		case 12 : max = 31;
		break;
		case 2 : max = feb;
		break;
		case 4 : max = 30;
		break;
		case 6 : max = 30;
		break;
		case 11 : max = 30;
		break;
		case 9 : max = 30;
		break;
	}

    if (mm < 1 | mm > 12)
    {
		bTrue = false;
		arguments.IsValid=false;
    }
    if (dd < 1 | dd > max)
    {
		bTrue = false;
		arguments.IsValid=false;   
    }
    if (bTrue)
    {
		arguments.IsValid=true;
	}
}
function validateSingleDate(datum) {
       /* This function checks that the input date is a valid date of the form yyyy-mm-dd */
  
      if (datum.length != 10)
             return false;
        if (datum.charAt(4) != "-")
              return false;
        if (datum.charAt(7) != "-")
             return false;

        yys = datum.substring(0,4);
        if (isNaN(yys))
           return false;
        else
           yy = parseInt(yys,10);

        mms = datum.substring(5,7);
        if (isNaN(mms))
           return false;
        else
           mm = parseInt(mms,10);

        dds = datum.substring(8,10);
        if (isNaN(dds))
           return false;
        else
           dd = parseInt(dds,10);

        if ((yy % 4) == 0)
           feb = 29;
        else
           feb = 28;

        max = 0;
        switch (mm){
           case 1 : max = 31;
           break;
           case 3 : max = 31;
           break;
           case 5 : max = 31;
           break;
           case 7 : max = 31;
           break;
           case 8 : max = 31;
           break;
           case 10 : max = 31;
           break;
           case 12 : max = 31;
           break;
           case 2 : max = feb;
           break;
           case 4 : max = 30;
           break;
           case 6 : max = 30;
           break;
           case 11 : max = 30;
           break;
           case 9 : max = 30;
           break;
        }

        if (mm < 1 | mm > 12)
              return false;
        
        if (dd < 1 | dd > max)
              return false;
   
    
        return true;
}

function isOldDate(formName,fName,t){
/*datumet bör vara ett validerat datum när det skickas in här */
	var now = new Date();
	new String(now.getFullYear().toString());
     year = new String(now.getFullYear().toString());
     month = new String(now.getMonth().toString());
     day = 	new String(now.getDate().toString());
     y = parseInt(year,10);
     m = parseInt(month,10);
    d = parseInt(day,10);
	var theForm;
	theForm = setForm(formName);    

     datum = theForm.elements[fName].value;

    yys = datum.substring(0,4);
        if (isNaN(yys))
           return true;
        else
           yy = parseInt(yys,10);

        mms = datum.substring(5,7);
        if (isNaN(mms))
           return true;
        else
           mm = parseInt(mms,10);

        dds = datum.substring(8,10);
        if (isNaN(dds))
           return true;
        else
           dd = parseInt(dds,10);

     if (yy < y) {
          alert(t);
          theForm.elements[fName].focus();
          return true;
     }
     else if (yy == y) {
          if (mm < m) {
               alert(t);
               theForm.elements[fName].focus();
               return true;
          }
          else if (mm == m) {
               if (dd <= d) {
                    alert(t);
                    theForm.elements[fName].focus();
                    return true;
               }
           }
      }     
      return false;

}

function isLaterDate(formName,dateField1,dateField2,t){
/*datumen bör vara validerade när de skickas in här. Om datum1 är senare än eller lika med datum2 så returneras true*/
		var theForm;
		theForm = setForm(formName);
	
        dateField1 =theForm.elements[dateField1].value;
        yys = dateField1.substring(0,4);
        if (isNaN(yys))
           return true;
        else
           y = parseInt(yys,10);

        mms = dateField1.substring(5,7);
        if (isNaN(mms))
           return true;
        else
           m = parseInt(mms,10);

        dds = dateField1.substring(8,10);
        if (isNaN(dds))
           return true;
        else
           d = parseInt(dds,10);

     fName = dateField2;
     datum = theForm.elements[fName].value;

    yys = datum.substring(0,4);
        if (isNaN(yys))
           return true;
        else
           yy = parseInt(yys,10);

        mms = datum.substring(5,7);
        if (isNaN(mms))
           return true;
        else
           mm = parseInt(mms,10);

        dds = datum.substring(8,10);
        if (isNaN(dds))
           return true;
        else
           dd = parseInt(dds,10);

     if (yy < y) {
          alert(t);
          theForm.elements[fName].focus();
          return true;
     }
     else if (yy == y) {
          if (mm < m) {
               alert(t);
               theForm.elements[fName].focus();
               return true;
          }
          else if (mm == m) {
               if (dd <= d) {
                    alert(t);
                    theForm.elements[fName].focus();
                    return true;
               }
           }
      }     
      return false;
}

/*Functions for adding (add) and removing (remove)
  multiple values between two selection lists */
function addSelections(formName, selectName, selectedName){

	var theForm;
	theForm = setForm(formName);
	
	selectObj = theForm.elements[selectName];
	selectedObj = theForm.elements[selectedName];
						
	for (var i = 0; i < selectObj.length;i++ ) {
		if (selectObj.options[i].selected == true) {
			currentValue = selectObj.options[i].value;
			currentText = selectObj.options[i].text;
						
			var option0 = new Option(currentText, currentValue);
			selectedObj.options[selectedObj.length] = option0;
			selectObj.options[i] = null;
			i--;		
		}
		
	}	
}
					
function removeSelections(formName, selectName, selectedName){
	var theForm;
	theForm = setForm(formName);

	selectObj = theForm.elements[selectName];
	selectedObj = theForm.elements[selectedName];
					
	for (var i = 0; i < selectedObj.length;i++ ) {
		if (selectedObj.options[i].selected == true) {						
			currentValue = selectedObj.options[i].value;
			currentText = selectedObj.options[i].text;
				
			var option0 = new Option(currentText, currentValue);
			selectObj.options[selectObj.length] = option0;
			selectedObj.options[i] = null;
			i--;
		}
		
	}						
}

/*Function that returns a comma-separated string with id:s
  from a selection list */
function getIds(selectName){
	var strIds = "", strTmpId = "";
	theForm = setForm(0);
	
	selectObj = theForm.elements[selectName];
		
	for (var i = 0; i < selectObj.length; i++){
		strId = selectObj.options[i].value;

		//Do not start the string with a comma
		if (!containsValue(strIds)) strIds = strId;
		else strIds = strIds + "," + strId;
	}

	return strIds;
}

function validateTime(source, arguments)
{
	/*	This function checks that the input time field is a valid time of the form hh:mm 
		Use it with the CustomValidator!
	*/
	
	var time;
	var bTrue = true;
	time = arguments.Value;
	
	if (time.length != 5)
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	if (time.charAt(2) != ":")
		{
			bTrue = false;
			arguments.IsValid=false;   
			return;
		}
	
	hhs = time.substring(0,2);
	
	if (isNaN(hhs))
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	else
		{
			hh = parseInt(hhs,10);
		}

	mms = time.substring(3,5);
	
	if (isNaN(mms))
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	else
		mm = parseInt(mms,10);

	if (hh > 23 || mm >= 60 || mm < 0 || hh < 0)
		{
			bTrue = false;
			arguments.IsValid=false;
			return;
		}
	
    if (bTrue)
    {
		arguments.IsValid=true;
	}
}

function validateNumber(source, arguments)
{
	/*	This function checks that the input is a valid number 
		Use it with the CustomValidator!
	*/
	
	var val;
	val = arguments.Value;
	
	if (isNaN(val))
		{
			
			arguments.IsValid=false;
			
		}
	else
		{
			arguments.IsValid=true;
		}
	return;	
}

//Global variables
var objectList = new Array(); //Is used to sort
var col = 0; //the column to sort by 
var order = 0;  //0=asc and 1=desc
function sortSelect(sName,sortBy,sortDir){
	//sortBy can be either 'text' or 'value'
	//sortDir: 1=desc,0=asc
	//sName is the id of the select.
	objectList.length = 0;
	
	var theSel = document.getElementById(sName);
				
	for (x=0; x < theSel.length;x++){
		addObject(theSel[x].text,theSel[x].value);
	}
	
	if (sortBy == 'value'){
		col=1;
	}
	else{
		col=0;
	}
	
	sortList(col,sortDir);
	
	for (x=0;x < objectList.length;x++){
		
		theSel[x].value = objectList[x][1];
		theSel[x].text = objectList[x][0];
	}		
}
		
function addObject(){
	objectList[objectList.length] = arguments;
}
			
function qSort(i,j,R){
	var pivot;
	var pivotindex;
	var k;
	pivotindex = findPivot(i,j);
	
	if (pivotindex != -1){
		pivot = objectList[pivotindex][col];
		
		k = partition(i,j,pivot);
		
		qSort(i,k-1,5);
		qSort(k,j,5);
						
	}
}
function findPivot(i,j){
	var firstkey;
	var k;
	firstkey = objectList[i][col];
	
	for (k=i+1;k <=j ;k++){
		if (objectList[k][col] > firstkey){
			return k;
		}
		else if (objectList[k][col] < firstkey){
			return i;
		
		}
				
	}
	return -1;
}
function partition(i,j,pivot){
	var l = i;
	var r = j;
	
	do{
		swap(l,r);
		if (order == 1){
			while (objectList[l][col] >= pivot){
				
				l++;
			}
			while (objectList[r][col] < pivot){
				r--;
			}
		}	
		else{
			while (objectList[l][col] < pivot){
				
				l++;
			}
			while (objectList[r][col] >= pivot){
				r--;
			}
		}			
	} while (l <= r)

	return l;
}
function swap(l,r){
	var x = l;
	var y = r;
					
	var tmp=objectList[x];
	objectList[x]=objectList[y];
	objectList[y]=tmp;
		
}		
function sortList(byCol,sortOrder){
	order = sortOrder;
	col = byCol;
	qSort(0,objectList.length-1,5);	
}
// Usage: Create a hidden field called okCancel in a form
// with the id denoted by formId. When the user accepts the 
// dialog the form is submitted and the value from the dialog
// is stored in the hidden field.
// param query: The text displayed in the ok cancel dialog
// param formId: The form that is submitted by pressing ok in the dialog
// param fieldId: The hidden field where the ok-value is stored
function okCancelDialog(query, formId, fieldId) {
	var doDelete = window.confirm(query);
	if (doDelete) {
		eval("document.getElementById('" + fieldId + "').value = " + doDelete);
		document.forms[formId].submit();
	}
}

//Usage: Call this function from the onkeypress-event at a textbox.
//The function checks if the key is the enterkey and if it is,
//the button with the id in toBeClicked will receive a click-event.
function simulateClickByEnterkey(toBeClicked)
{
	if (window.event.keyCode==13)
	{
		document.getElementById(toBeClicked).click();	  	
	}
}

function replaceSubString(theString,stringToReplace,replaceString){
 l = stringToReplace.length;
 i = theString.indexOf(stringToReplace);
 while (i > -1){
  t = theString.substring(i+l);
  theString = theString.substring(0,i) + replaceString + t;
  i = theString.indexOf(stringToReplace);
 }
 return theString;
}

function dropDown(id){
	showId = 'leftN' + id;
	lNav = document.getElementById('leftNav');
	for(i = 0;i<lNav.all.length;i++){
		no = lNav.all[i];
		if (no.id.indexOf('leftN') > -1){
			nav = no;
			for(j = 0;j<nav.all.length;j++){
				o = nav.all[j];
				if (o.id.indexOf('lvl3') == -1){
					if (no.id != showId)
						o.style.display = 'none';
					
				}	
			}
		}
	}

	nav = document.getElementById(showId);
	for(i = 0;i<nav.all.length;i++){
		o = nav.all[i];
		if (o.id.indexOf('lvl3') == -1)
			o.style.display = '';
			//o.style.display = (o.style.display == '') ? 'none':'';
	}
}

function goTo(id,type,link,own,lvl,path,style){
	var today = new Date();
	var msek = today.getTime();
	var rnd = "&rnd1=" + msek;

	loc = window.location.href.toLowerCase();
	//link = link.toLowerCase();
	isAdmin = (loc.indexOf('admindefault.aspx') > -1);
	
	if (isAdmin){
		loc = path + '/Portal/admindefault.aspx?areaid=' + id;
	}
	else{
		if (type==3){
			
			//special för utveckling 
			if (link.toLowerCase().indexOf('/') == 0 && loc.indexOf('/polistidningen_parc_web') > -1 && link.toLowerCase().indexOf('/polistidningen_parc_web') == -1){
				link = '/Polistidningen_Parc_Web' + link;
			}
			
			if (link.indexOf('?') > -1){
				loc = link + '&areaid=' + id + rnd;
			}
			else{
				loc = link + '?areaid=' + id + rnd;
			}
			
		}
		else{
			if (type==1){
				loc = path + '/Portal/Default.aspx?areaid=' + id + rnd;
				if (lvl==3)
					loc = loc + '&drp=' + id;
			}
			else{
				dropDown(id);
				return;
			}	
		}
	}
	
	if (own==1 && !isAdmin){
		window.open(loc,'win' + id,style)
	}
	else{
		window.location.href = loc;
	}	
	
}

function toggle(mode, path){
	loc = window.location.href.toLowerCase();
	newloc = '';
	if (loc.indexOf('default.aspx') == -1){
		i = loc.indexOf('?');
		query = loc.substring(i);
		newloc = path + '/portal/admindefault.aspx' + query;
	}
	else{
		if (mode == 'on'){
			newloc = loc.replace('/default.aspx', '/admindefault.aspx');
		}
		else{
			newloc = loc.replace('/admindefault.aspx', '/default.aspx');
		}
	}	
	
	window.location.replace(newloc);
	
}

