
//Use counter for the loader, to avoid it being disabled before we're done with it
var loadCount = 0;
var g_activeTab = 0;

var g_changed = new Array();

var g_hasChanged = false;

var g_uploadWindow = 0;

var g_contentWindow = 0;

function set_content(content_destination, content_mime_destination)
{

	var dest = document.getElementById(content_destination);
	
	if (dest != null)
	{
		var currentMime = "";
		var s = document.getElementById(content_mime_destination);
		if (s != null)
		{
			currentMime = s.value;
		}
	
		g_contentWindow = window.open('set_content.php?content_destination=' + content_destination + '&current_content='+dest.value + '&content_mime_destination=' + content_mime_destination + "&current_mime=" + currentMime,'mywin','menubar=0,width=500,height=200,toolbar=0,resizable=0,status=0,scrollbars=1');
	}	
}

function set_content_done(content_destination, content_mime_destination)
{
	var dest = document.getElementById('content_file');
	var src = opener.document.getElementById(content_destination);
	if (dest != null && src != null)
	{
		src.value = dest.value;
	}
	
	dest = document.getElementById('content_mime');
	src = opener.document.getElementById(content_mime_destination);
	if (dest != null && src != null)
	{
		src.value = dest.value;
	}
	
	window.close();
}

function fetch_help(source)
{
	//alert(source);
//	window.open(source,'mywin','width=500,height=500,toolbar=0,resizable=0,scrollbars=1,alwaysRaised=yes');
	var target = document.getElementById('help_frame_main');
	if (target != null)
	{
		target.style.display = "block";
		ajax_fetch(source, 'help_frame');
	}
}

function img_upload(destination)
{
	var dest = document.getElementById(destination);
	if (dest != null)
	{
		g_uploadWindow = window.open('upload_image.php?destination=' + destination + '&current='+dest.value,'mywin','width=500,height=500,toolbar=0,resizable=0,scrollbars=1');
	}	

}

function img_upload_done(destination)
{
	var dest= document.getElementById('img_file_id');
	var src = opener.document.getElementById(destination);
	if (dest != null && src != null)
	{
		src.value = dest.value;
	}
	window.close();
}

function showCurrentCollapsed(view)
{
	var g_currentCollapsed = session_read(view);
	if (g_currentCollapsed != "" && g_currentCollapsed != 0)
	{
	//	alert(g_currentCollapsed);
		var current = document.getElementById(g_currentCollapsed + "_2");
		var icon = document.getElementById(g_currentCollapsed + "_icon");
		var c = 2;
		while (current != null)
		{
			current.style.display = "inline";
			c++;
			current = document.getElementById(g_currentCollapsed + "_" + c);
			icon.innerHTML = "-";
		}
	}
}

function toggleRowCollapse(view, id)
{
	var g_currentCollapsed = session_read(view);
	if (g_currentCollapsed != "" && g_currentCollapsed != id)
	{
		//alert(g_currentCollapsed);
		var current = document.getElementById(g_currentCollapsed + "_2");
		var icon = document.getElementById(g_currentCollapsed + "_icon");
		var c = 2;
		while (current != null)
		{
			current.style.display = "none";
			c++;
			current = document.getElementById(g_currentCollapsed + "_" + c);
			icon.innerHTML = "+";
		}
	}
	
	var target = document.getElementById(id + "_2");
	var icon = document.getElementById(id + "_icon");
	var count = 2;
	while (target != null)
	{
		if (target.style.display == "none")
		{
			target.style.display = "inline";
			icon.innerHTML = "-";
		}
		else
		{
			target.style.display = "none";
			icon.innerHTML = "+";
		}
		count++;
		g_currentCollapsed = id;
		target = document.getElementById(id + "_" + count);
	}
	
	session_write(view, g_currentCollapsed);
}

function clearErrors()
{
	//alert("clearing errors");
	var errorFrame = document.getElementById('error_frame');
	if (errorFrame == null)
		return;
	//errorFrame.style.display = "none";	
	errorFrame.innerHTML = " ";
	errorFrame.style.backgroundColor = "#314D8C";
}

function reportError(msg, noError)
{
	var errorFrame = document.getElementById('error_frame');
	if (errorFrame == null)
		return;
	//errorFrame.style.display = "block";	
	errorFrame.innerHTML = "";
		
	if (noError)
	{
		errorFrame.style.backgroundColor = "#22EE22";
	}
	else
	{
		errorFrame.style.backgroundColor = "#EE2222";
		//errorFrame.innerHTML = "Feil: ";
	}
	errorFrame.innerHTML = errorFrame.innerHTML + msg;
	
	document.getElementById('message_frame').style.display = "block";
	var image = "success.png";
	if (!noError)
		image = "error.png";
	document.getElementById('message_frame').innerHTML = '<img width="32px" height="32px" src="icons/' +  image + '" border="0"><br />' + msg;
}

function ieOptionEvntFallback(sender)
{
	if (BrowserDetect.browser == "Explorer")
	{
		//Preform the fallback for the lack of events on <option> tags in explorer.
		//What we want to do, is to simply execute the event for the selected option. So just get the option, get event, and eval it or something.
		sender.options[sender.selectedIndex].click();
		//alert(sender.options[sender.selectedIndex].innerHTML);
	}
}

window.onload=function(){
	//g_changed = new Array();
	//session_init();
	
	g_hasChanged = false;
//	showCurrentCollapsed();
	
}

window.onbeforeunload=function(){
	//session_save();
	
}
//*/
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}

function showError(parent, message)
{
	var dest = document.getElementById('error_div');
	//dest.style.display = "block";
	/*dest.innerHTML = '<table><tr>';
	dest.innerHTML += '<td valign="top"><img width="30%" height="30%" alt="error icon" src="images/error.png"/></td>';
	dest.innerHTML += '<td valign="top">' + message + '</td>';
	dest.innerHTML += '</tr></table>';	
	*/
	parent.title = message;
}

function hideError()
{
	//var dest = document.getElementById('error_div');
	//dest.style.display = "none";
}

function modifyChanged(highlight)
{
	var i = 0;
	for (i = 0; i < g_changed.length; i++)
	{
		if (highlight)
		{
			g_changed[i].style.border = "1px solid #FF0000";
			//g_changed[i].style.color = "#FFFFFF";
		}
		else
		{
			g_changed[i].style.border = "1px solid #999999";
		}
	}
}

function iHaveChanged(sender)
{
	//alert(sender.style);
	sender.style.border = "1px solid #FF0000";
	g_hasChanged = true;
	g_changed.push(sender);
	//alert("Changed " + sender.name);
}

function confirmLeave(url)
{		
	if (g_changed.length == 0 || confirm("Leaving this page will discard all changes.\nContinue?"))
	{
		if (url != "")
			window.location = url;
		else 
			return true;
		
	}
	modifyChanged(true);
	if (url == "")
		return false;
	
}

/////////////////////////////////////////////////////////////////////////

function uploadFile(formName)
{
	document.getElementById(formName).target = 'upl_target'; 
	document.getElementById(formName).submit();
}

function uploadDone(destination)
{
	document.getElementById(destination).innerHTML = document.getElementById('upl_target').contentWindow.document.body.innerHTML;
}


/////////////////////////////////////////////////////////////////////////

function showLoader() {
    loadCount++;
    document.getElementById('loader').style.display = 'block';
	document.getElementById('message_frame').style.display = 'none';
    //document.getElementById('loader').innerHTML = '<br /><center>Working.. <br /><img src="ajax-loader.gif"></center><br />';
}

function hideLoader() {
    loadCount--;
    if (loadCount == 0) {
        document.getElementById('loader').style.display = 'none';
        //document.getElementById('loader').innerHTML = '';
    }
}

function ajax_postFormWithDest(sender, name, url, destination) {
    modifyChanged(false);
	g_changed = new Array();
    var the_form = document.getElementById(name);
    destination = document.getElementById(destination);
    var the_data = '';
    for (i = 0; i < the_form.length; i++) {

        var element = the_form.elements[i];
        if (element.type != "button") {
            if (element.type == "checkbox")
                if (element.value == "on")
                    the_data = the_data + element.name + '=1&';
                else
                    the_data = the_data + element.name + '=0&';
            else
                the_data = the_data + element.name + '=' + element.value + '&';
        }
    }
    the_data = (the_data + sender + '=1');

    showLoader();

    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");

                return false;
            }
        }
    }
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            //document.myForm.time.value=xmlHttp.responseText;
            destination.innerHTML = xmlHttp.responseText;
            hideLoader();
        }
    }
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
    xmlHttp.send(the_data);

    return true; //*/
}

function ajax_postForm(sender, name, url) {
    modifyChanged(false);
	g_changed = new Array();
    var the_form = document.getElementById(name);
    var destination = the_form.parentNode.id; //This wont work for list/table views. Thats ok though, it's not supposed to.
    var the_data = '';
    for (var i = 0; i < the_form.length; i++) {

        var element = the_form.elements[i];
        if (element.type != "button") {
            if (element.type == "checkbox")
			{
                if (element.checked)
                    the_data = the_data + element.name + '=1&';
                else
                    the_data = the_data + element.name + '=0&';
			}
            else
                the_data = the_data + element.name + '=' + element.value + '&';
        }
    }
    the_data = (the_data + sender + '=1');

    showLoader();

    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");

                return false;
            }
        }
    }
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            //document.myForm.time.value=xmlHttp.responseText;
            document.getElementById(destination).innerHTML = xmlHttp.responseText;
            hideLoader();
			
			var el = document.getElementById(destination + "_load_script");
			
			if (el != null)
			{
				//alert("Executing script:\n" + el.innerHTML);
				eval(el.innerHTML);
			}
        }
    }
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
    xmlHttp.send(the_data);

    return true; //*/
}

function ajax_postFetch(source, destination, postdata) {

    showLoader();

    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");

                return false;
            }
        }
    }
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            //document.myForm.time.value=xmlHttp.responseText;
            document.getElementById(destination).innerHTML = xmlHttp.responseText;
            hideLoader();
        }
    }
    xmlHttp.open("POST", source, true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
    xmlHttp.send(postdata);

    return true; //*/
}

function browse_files(id)
{
	document.getElementById(id).click();
}

function ajax_fetch(source, destination) {
	if (source == "" || source == null || destination == "_div")
	return;
	clearErrors();
    showLoader();
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");

                return false;
            }
        }
    }
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            //document.myForm.time.value=xmlHttp.responseText;
            document.getElementById(destination).innerHTML = xmlHttp.responseText;
			var el = document.getElementById(destination + "_load_script");
			
			if (el != null)
			{
				//alert("Executing script:\n" + el.innerHTML);
				eval(el.innerHTML);
			}
            hideLoader();
        }
    }
    xmlHttp.open("GET", source, true);
    xmlHttp.send(null);

    return true; //*/
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////




function collapse(sender, target)
{
	target = document.getElementById(target);
	if (target.style.display == "none") 
	{
		//sender.innerHTML = '<img src="icons/icon_collapse.png" border = "0" />';
		target.style.display = "block";
	}
	else
	{
		//sender.innerHTML = '<img src="icons/icon_expand.png" border = "0" />';
		target.style.display = "none";
	}
}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* Sets the "sender" tab to the selected tab and loads the page specified in url into the Tab Control. */
function setAsActiveTab(sender, url) {
    var tabcontrol = document.getElementById('tab_control');
    if (g_activeTab == 0)
        g_activeTab = document.getElementById('tab_item1');
    g_activeTab.className = "tabbedMenuItem_inactive";
    sender.className = "tabbedMenuItem_active";
    g_activeTab = sender;
    //alert(sender);
    ajax_fetch(url, 'tab_control');
}

function putNChecklistDataInForm(sender, id) {
	var dest_field = document.getElementById(id);
    if (dest_field != null)
	{
		//Final Format: ID,C1,C2,C3;ID,C1,C2,C3;....
		var the_data = "";
		var last_id = null;
		var elements = document.getElementById(id + '_nchecklist').getElementsByTagName('input');
		for (i = 0; i < elements.length; i++) 
		{
			var element = elements[i];
			if (element.type == "checkbox" && element.name != null) 
			{
				//the_data = the_data + element.name;
				if (last_id != element.id)
				{
					if (last_id != null)
						the_data += ';';
					last_id = element.id;
					
					the_data += element.id;
				}
				if (element.checked == true)
					the_data += ",1";
				else
					the_data += ",0";
			}
		}

		dest_field.value = the_data;
	}
	else
	{
		alert("Advarsel! Kunne ikke hente data fra checklist (Feilkode C02)");
	}
}

function putChecklistDataInForm(sender, id) { //id is the pure name of the source
    
	var dest_field = document.getElementById(id);
    if (dest_field != null)
    {
		dest_field.value = constructParListFromCheckboxes(id + '_checklist');
	}
	else
	{
		alert("Advarsel! Kunne ikke hente data fra checklist (Feilkode C01)");
	}
		//alert( dest_field.value + " put in " + id);
}

function constructParListFromCheckboxes(form_name) {
 //   var the_form = document.getElementById(form_name);
    var the_data = '';
    var count = 0;
	var source = document.getElementById(form_name);
	if (source != null)
	{
		var elements = document.getElementById(form_name).getElementsByTagName('input');
	
		for (i = 0; i < elements.length; i++) {

			var element = elements[i];
			if (element.type == "checkbox" && element.name != null) {
				if (count > 0) {
					the_data = the_data + ';';
				}
				the_data = the_data + element.name;
				if (element.checked == true)
					the_data += ",1";
				else
					the_data += ",0";
				count++;
			}
		}
		if (the_data != '')
			the_data = the_data + ';'; 
	}
    return the_data;
}

function selectAllCheckboxes(form_name) {

	var elements = document.getElementById(form_name).getElementsByTagName('input');
    for (i = 0; i < elements.length; i++) {
        var element = elements[i];
        if (element.type == "checkbox") {
            element.checked = true;
        }
    }
}

function selectAllCheckboxesMultipleForms(prototypename) {
	alert(prototypename);
	var i = 0;
	var the_form = document.getElementById(prototypename + i);
	while(the_form != null)
	{
		for (i = 0; i < the_form.length; i++) {
			var element = the_form.elements[i];
			if (element.type == "checkbox") {
				element.checked = true;
			}
		}
		the_form = document.getElementById(prototypename + i);
		i++;
	}
	
}

function unselectAllCheckboxes(form_name) {
    var elements = document.getElementById(form_name).getElementsByTagName('input');
    for (i = 0; i < elements.length; i++) {
        var element = elements[i];
        if (element.type == "checkbox") {
            element.checked = false;
        }
    }
}

///////////////////////////////////////////////////////////////////////////
//Validation



function validate_non_empty(field, errormsg) {
   
    if (errormsg == '')
        errormsg = "One or more required fields are empty";
    with (field) {
        if (value == null || value == "") {
            alert(errormsg); return false;
        }
        else {
            return true;
        }
    }
}

function validate_text(field, errormsg) {


}

function validate_number(field, errormsg) {

}

function validate_email(field, errormsg) {
    if (errormsg == '')
        errormsg = field.value + " is not an e-mail address!";
    with (field) {
        apos = value.indexOf("@");
        dotpos = value.lastIndexOf(".");
        if (apos < 1 || dotpos - apos < 2) {
            alert(errormsg); return false; 
        }
        else {
            return true; 
        }
    }
}
