var inView = null;

function toggleSection( sectionID, display )
{
	var section = document.getElementById( sectionID );
	
	if (display)
	{
		section.style.display = 'block';
	}
	else
	{
		section.style.display = 'none';
	}
}

function incidentToggle ( )
{
	var select = document.getElementById( 'incidentSelect' );
	var sectionToToggle = select.options[select.selectedIndex].value;
	
	if (inView != null)
	{
		var hideSection = document.getElementById( inView );
		hideSection.style.display = 'none';	
	}
	
	if (sectionToToggle != '')
	{
		var sectionID = 'incidentSection' + sectionToToggle;
		var section = document.getElementById( sectionID );
			
		section.style.display = 'block';
		inView = sectionID;	
	}
}

function initVisibleSections()
{
	if (document.reportForm['agency[selected]'][0].checked)	
	{
		toggleSection('agencyForm', true);
	}
	if (document.reportForm['child[selected]'][0].checked)	
	{
		toggleSection('childVictimForm', true);
	}
	if (document.reportForm['suspect[selected]'][0].checked)	
	{
		toggleSection('suspectForm', true);
	}
	if (document.reportForm['reporter[selected]'][0].checked)	
	{
		toggleSection('reporterForm', true);
	}
	if (document.reportForm['lea[selected]'][0].checked)	
	{
		toggleSection('LEAForm', true);
	}
	toggleOther( 'relationSelect', 'relationOther');
	toggleOther( 'suspectRelation', 'suspectRelationOther' );
	toggleEmail();
}

function hidePopup(elem)
{
    var id = 'popupBox';
    if(elem)
    {
        id += elem;
    }
	var popup = document.getElementById(id);
	
	popup.style.visibility = 'hidden';
}

function toggleOther( selectId, id )
{
	var div = document.getElementById( id );
	var select = document.getElementById(selectId);
	var value = select.options[select.selectedIndex].value;
	
	if ((value == "Other") || (value == "Autre") || (value == 19) )
	{
		div.style.display = 'block';
	}
	else
	{
		div.style.display = 'none';
	}
}

function toggleEmail()
{
	var div = document.getElementById('emailIncident');
	var checkedValue;

	for (var i=0; i< document.reportForm['incident[spam_id]'].length; i++)
	{
		if (document.reportForm['incident[spam_id]'][i].checked)  checkedValue = document.reportForm['incident[spam_id]'][i].value
	}
	
	if (checkedValue == 'new') 
	{
		div.style.display='block';
	}
	else
	{
		div.style.display='none';
	}
}

function validate_no_url(objId)
{
	var errStr = "{ NO_URL_IN_DESCRIPTION }";
	
	if(document.getElementById(objId).value.toLowerCase().match(/.*http:.*/))
	{
		document.getElementById(objId).value = errStr;
	}
	if(document.getElementById(objId).value.toLowerCase().match(/.*https:.*/))
	{
		document.getElementById(objId).value= errStr;
	}
	if(document.getElementById(objId).value.toLowerCase().match(/.*www\..*/))
	{
		document.getElementById(objId).value= errStr;
	}	
}
function selecttzo() {
	/* I shouldn't do this so many times if we don't need them all */
	var stdeuoffset = (new Date("26 Oct 2003").getTimezoneOffset()/60)*(-1); // this is EU standard time?
	var stdoffset = (new Date("01 Jan 2007").getTimezoneOffset()/60)*(-1);	//this is Standard Time
    var curoffset=(new Date().getTimezoneOffset()/60)*(-1);
	var realoffset = curoffset;
	if(stdeuoffset != curoffset)
	{
		realoffset = stdeuoffset;
	}else if(stdoffset != curoffset)
	{
		realoffset = stdoffset;
	}
	
	var obj=document.getElementById('required[incidentTimeZone]');
	if(obj) /* since we aren't just on the report page */
	{
		if(obj.selectedIndex == 0)
		{
			for (var i=0; i<obj.options.length; i++) {
				if(obj.options[i].value == stdoffset) {
					obj.options[i].selected = 1;
				}
			}
		}
	}
		
}
function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}

addEvent(window, 'load', selecttzo);
//addEvent(window, 'beforeunload', savesession);

/* new report form */

showInfo = function(num,array)

{
    if(array[num])
    {
        new Effect.SlideDown(array[num], {
					duration: 0.3
		});
    }
    
}
updatedInfo = function(obj,cls,array)
{
    $$('.'+cls).invoke('hide');
    showInfo(obj.value,array);
   
}
showSelected = function(cls,array)
{
    $$('.'+cls).each(function(item){
        
        if(item.checked)
        {
            showInfo(item.value,array);
        }
    
    });
}
showCollapsible = function(child)
{
    /* hide all */
    if($('collapsible_container'))
    {
        $('collapsible_container').childElements().each(function(item){
            /* a little bit ugly */
            item.firstDescendant().firstDescendant().innerHTML = item.select('.minimizedtitle').pluck('value').join(' ');
            item.select('div.maximized').invoke('hide');
            item.select('div.minimized').invoke('show');
            
        })
        
        child.select('div.maximized').invoke('show');
        child.select('div.minimized').invoke('hide');
    }
}
updateCollapsible = function()
{
    if($('collapsible_container'))
    {
        showCollapsible($('collapsible_container').childElements().last());    
    }
    
}
addCollapsible = function(template)
{
    var newNode=document.createElement('div');
    newNode.innerHTML = $(template).innerHTML;
    newNode.className = $(template).className;
    $('collapsible_container').appendChild(newNode);
    showCollapsible(newNode);
}
deleteCollapsible = function(obj)
{
    $('collapsible_container').removeChild(obj);
}
Event.observe(window, 'load', function() {
    
    
    $$('.example_link').each(function(item) {
        Event.observe(item,'click',function() {
            if($(item.id+'_info'))
            {
                $(item.id+'_info').toggle(); 
            
            }
        });
    })
    updateCollapsible();
    
    
});

Validation.add('validate-one-required-gp', 'Please select one of the above options', function (v,elm) {
    /* need to make my own to get grandparent */
    var p = elm.parentNode.parentNode;
    var options = p.getElementsByTagName('INPUT');
    return $A(options).any(function(elm) {
        return $F(elm);
    });
});

Validation.add('validate-age','Must be a number between 0 and 110', {
    include : ['validate-digits'],
    min: 0,
    max: 110
    
});

var extrainfoCnt = 0;

function addinfo(prefix, fieldid, divid, datadivid, skipvalidation){
    var holder = $(divid);
    var fieldholder = $(datadivid);
    var thedata = $(fieldid).value;

    /* seems to be the easiest way to get it to do what I want */
	
	// breaks victim/suspect validation, so allowing you to skip it.
	if(skipvalidation){
		res = true;
	}
	else{
		$(fieldid).addClassName('required');
		Validation.reset(fieldid);
		var res = Validation.validate($(fieldid));
		$(fieldid).removeClassName('required');
	}
   
    if(res)
    {
        holder.innerHTML += '<div id="' + prefix + extrainfoCnt + '">' + 
        '<img onclick="remove_infoitem(\'' + prefix + '\', \'' + extrainfoCnt + '\');" alt="{ REMOVE }" title="{ REMOVE }" src="/images/icons/delete.png" style="cursor: pointer;" class="applyIconBorder" />&nbsp;' +
        thedata +
        '</div>';
        
        fieldholder.innerHTML += '<div id="' + prefix + 'fields' + extrainfoCnt + '">' +
        '<input type="hidden" name="' + prefix + '_' + extrainfoCnt + '" id="' + prefix + '_' + extrainfoCnt + '" value="' + thedata + '" class="' + prefix + '" />' +
        '</div>';
        
        $(fieldid).value = '';
        
        if(!holder.visible()){
            holder.appear();
        }
        
        extrainfoCnt ++;		
    }
    
	
    
}

function remove_infoitem(prefix, numbah){
    var thedisplay = $(prefix + numbah);
    var thefields = $(prefix + 'fields' + numbah);
    var container = thedisplay.up('.extra_info');
    thedisplay.hide();
    thedisplay.remove();
    thefields.remove();

    /* if we don't have any items, hide */
    var size = container.childElements().size();
    if(size < 1)
    {
        container.hide();
    }

	

}

function expand_extrainfo(datafieldid, prefix, fieldid, divid, datadivid, subdelimiter){
	var datalist = $(datafieldid).value; // assuming multiples will be in a comma-delimited list
    if(datalist != ''){
		var arr_data = datalist.split(',');
		for(var i = 0; i<arr_data.length; i++){
            
			if(i == (arr_data.length - 1)){ // single out the last one to fill in the form field
				if(subdelimiter){
					var maindata;
					var subdata;
					if(arr_data[i].indexOf(subdelimiter) != -1){ 
						var splittah = arr_data[i].split(subdelimiter);
						maindata = splittah[0];
						subdata = splittah[1];
					}
					else{
						subdata = '';
						maindata = arr_data[i];
					}
					
					if(datafieldid.indexOf('ip_address') != -1){
                        
						var arr_ipaddress = maindata.split('.');
						
						for(eye=1;eye<=4;eye++){
							$(prefix + '_o' + eye).value = arr_ipaddress[eye - 1];
						}
						$(prefix + '_port').value = subdata;
					}
					else{
						$(prefix + '_main').value = maindata;
						$(prefix + '_sub').value = subdata;
					}
				}
				else{
					$(fieldid).value = arr_data[i];
				}
			}
			else{
				$(fieldid).value = arr_data[i];
				addinfo(prefix, fieldid, divid, datadivid)
			}
		}
	}
    /*else    //clear values
    {
        
        for(var eye = 1;eye <= 4;eye++)
        {
            $(prefix + '_o' + eye).value = '';
            
        }
        $(prefix + '_port').value = '';
    }*/
}

function consolidate_extrainfo(classname, fieldid){
	var items = '';
	$$('.' + classname).each(function(item){
		if(items != ''){
			items += ',';
		}
		items += item.value;  
	});
	$(fieldid).value = items;
}
function cleanup_extrainfo(datadivlist){
	if(datadivlist){
		var arr_datadivids = datadivlist.split(',');
		for(var i = 0; i<arr_datadivids.length; i++){
			$(arr_datadivids[i]).select('div').invoke('remove');
			$(arr_datadivids[i]).hide();
		}
	}
}

function addinfo_ip(prefix, fieldid, divid, datadivid, finalizeonly){
	var theaddy = '';
	for(i=1;i<=4;i++){
		if(theaddy != ''){
			theaddy += '.';
		}
		theaddy += $(prefix + '_o' + i).value;
		$(prefix + '_o' + i).value = '';
	}
	
	// check for and add the port if it's been specified
	if($(prefix + '_port').value != ''){
		theaddy += ':' + $(prefix + '_port').value;
		$(prefix + '_port').value = '';
	}
	if(theaddy != ''){
		$(fieldid).value = theaddy;
        
		if(!finalizeonly){
			addinfo(prefix, fieldid, divid, datadivid, 1);
		}
	}
}

function addinfo_phone(prefix, fieldid, divid, datadivid, finalizeonly){
	var thenumber = '';
	
	thenumber = $(prefix + '_main').value;
	if($(prefix + '_sub').value != ''){
		thenumber += 'x' + $(prefix + '_sub').value;
	}
	$(prefix + '_main').value = '';
	$(prefix + '_sub').value = '';
	if(thenumber != ''){
		$(fieldid).value = thenumber;
        
		if(!finalizeonly){
			addinfo(prefix, fieldid, divid, datadivid, 1);
		}
	}
}

function showhelp(divid, mode){
	if(mode){
		if(mode == 1){
			$(divid).appear();
		}
		else{
			$(divid).fade();
		}
	}
	else{
		if($(divid).visible()){
			$(divid).fade();
		}
		else{
			$(divid).appear();
		}
	}
}

function toggleitem(elementid,type,linkid,linktype,hidegrp,grpclassname,resizeviewport,viewportid,sourceid){
	if(elementid){
		if(type){
			switch(type){
				case 'slide':{
					if($(elementid).visible()){
						if(resizeviewport){
							Effect.SlideUp(elementid, {afterFinish: function () {
									$(viewportid).setStyle({
										'height': $(sourceid).getHeight() + 'px'
									})
								}
							});
						}
						else{
							Effect.SlideUp(elementid);
						}
					}
					else{
						if(hidegrp){
							if(hidegrp == 1){
								$$('.' + grpclassname).invoke('hide');	
							}
						}
						if(resizeviewport){
							Effect.SlideDown(elementid, {afterFinish: function () {
									/*$(viewportid).setStyle({
										'height': $(sourceid).getHeight() + 'px'
									})*/
									new Effect.Morph($(viewportid), {
										style: 'height: ' + $(sourceid).getHeight() + 'px',
										duration: 0.5
									});
								}
							});
						}
						else{
							Effect.SlideDown(elementid);
						}
					}
				}
				break;
				default:{
					if($(elementid).visible()){
						$(elementid).hide();
					}
					else{
						if(hidegrp){
							if(hidegrp == 1){
								$$('.' + grpclassname).invoke('hide');	
							}
						}
						$(elementid).show();
					}
				}
			}
		}
		if(linkid){
			switch(linktype){
				case 'icon':{
					if($(elementid).visible()){
						$(linkid).addClassName('iconclosed');
						$(linkid).removeClassName('iconopen');
					}
					else{
						$(linkid).addClassName('iconopen');
						$(linkid).removeClassName('iconclosed');
					}
				}
				break;
				default:{
					if($(elementid).visible()){
						$(linkid).innerHTML = '{ HIDE }';
					}
					else{
						$(linkid).innerHTML = '{ SHOW }';
					}
				}
			}
		}
		
	}
}

function toggle_pagehelp(divid){
	if(divid){
		if($(divid).visible()){
			help_slideout(divid);
		}
		else{
			help_slidein(divid);
		}
	}
}

function set_pagehelp(maindivid, contextdivid){
	if(maindivid){
		if(contextdivid){
			
			$(maindivid).select('div').invoke('hide');
			$(contextdivid).show();
			
			var parentdiv = $(maindivid).up();
			if((parentdiv.getHeight()) > ($(maindivid).getHeight())){
				$(maindivid).up().setStyle({
					'height': $(maindivid).getHeight() + 'px'
				});
			}
			else{
				parentdiv.morph('height: ' + $(maindivid).getHeight() + 'px');	
			}
		}
	}
}
function show_pagehelp(maindivid, formfield, value_array, showdivid, override){
	var index;
	var contextdivid;
	var doit = true;
	if(override){
		if(override == '1'){
			doit = false;
		}
	}
	if(doit){
		if(maindivid){
			if(showdivid){
				contextdivid = showdivid;
			}
			else{
				if(formfield.checked){
					index = formfield.value;
					contextdivid = value_array[index];
				}	
			}
			
			set_pagehelp(maindivid, contextdivid);
			if(!$(maindivid).visible()){
				help_slidein(maindivid);
			}
			else{
				var parentdiv = $(maindivid).up();
				if((parentdiv.getHeight()) > ($(maindivid).getHeight())){
					$(maindivid).up().setStyle({
						'height': $(maindivid).getHeight() + 'px'
					});
				}
				else{
					new Effect.Morph(parentdiv, {
						style: 'height: ' + $(maindivid).getHeight() + 'px',
						duration: 0.5
					});
					//parentdiv.morph('height: ' + $(maindivid).getHeight() + 'px');	
				}
				
			}
		}
	}
}

function help_slidein(divid){
	$(divid).show();
	new Effect.Move(divid, {x: 1, y: 0, mode: 'absolute', afterFinish: function() {
			new Effect.Morph($(divid).up(), {
				style: 'height: ' + $(divid).getHeight() + 'px',
				duration: 0.5
			});
			//$(divid).up().morph('height: ' + $(divid).getHeight() + 'px');
		}
	});
}
function help_slideout(divid, position){
	var xcoordinate = 308;
	if(position){
		xcoordinate = position;
	}
	new Effect.Move(divid, {x: xcoordinate, y: 0, mode: 'absolute', afterFinish: function() {
			$(divid).up().setStyle({
				'height': '75px'
			});
			$(divid).hide();
		}
	});
}

/*********************
 * generic script for adding multiple
 * technology types
 */

var techCnt = 0;

function addtech(listid, listheaderid, fieldsid, prefix, str_fields, displayfieldid, displayvalue){
    
    var list_container = $(listid);
    var fields_container = $(fieldsid);
    var fieldvalue = '';
	var fieldhtml = '';
	if(!displayvalue){
		displayvalue = $(displayfieldid).value;
	}
	var arr_fields = new Array();
	var fieldname = '';
	arr_fields = str_fields.split(',');
    if(list_container.innerHTML == ''){
        $(listheaderid).appear();
        list_container.appear();
    }
    list_container.innerHTML += '<div id="' + prefix + techCnt + '" style="display: none;">' +
    '<img onclick="remove_tech(\'' + prefix + '\', \'' + techCnt + '\', \'' + listid + '\', \'' + listheaderid + '\');" alt="Remove" title="Remove" src="/images/icons/delete.png" style="cursor: pointer;" class="applyIconBorder" />' +
    '<span><a href="#" id="' + prefix + techCnt + '_link" onclick="edit_' + prefix + '(\'' + techCnt + '\'); return false;">' + displayvalue + '</a></span>' + 
	'</div>';
    
    //fields_container.innerHTML += '<div id="' + prefix + 'fields' + techCnt + '">';
	for(i=0;i<arr_fields.length;i++){
		if($(arr_fields[i])){
			fieldvalue = $(arr_fields[i]).value;
			$(arr_fields[i]).value = '';
			
			/*//special case for our split up ip address fields
			fieldname = arr_fields[i];
			//console.log("fieldname has ipaddy? ", fieldname.indexOf('ip_address'));
			//console.log("fieldname is: ", fieldname);
			if(fieldname.indexOf('ip_address') != '-1'){
				for(z=1;z<=4;z++){
					//console.log("ordinal field: ", arr_fields[i] + '_o' + i);
					$(arr_fields[i] + '_o' + z).value = '';
				}
				$(arr_fields[i] + '_port').value = '';
			}*/
		}
		else{
			fieldvalue = '';
		}
        
        
        fieldhtml += '<input type="hidden" name="' + arr_fields[i] + '" id="' + arr_fields[i] + techCnt + '" value="' + escape(fieldvalue) + '" />';
        
	}
	fields_container.innerHTML += '<div id="' + prefix + 'fields' + techCnt + '">' + fieldhtml + '</div>';
    
    $(prefix + techCnt).appear();
    
    techCnt ++;
	
	// reset fields in case they were editing one and decided to add it as a new one
	$$('div.editing').invoke('removeClassName', 'editing');
	
	if($(prefix + '_savelink').visible()){
		$(prefix + '_savelink').fade();
	}
    
	$(prefix + '_addlink').innerHTML = $(prefix + "_add_text").value;
	$(prefix + '_editing').value = '';
    
	$$('.other_container').invoke('hide');
}

function remove_tech(prefix, index, listid, listheaderid){
    if($(prefix + '_editing').value == ''){
		var list_container = $(listid);
		var display_data = $(prefix + index);
		var data = $(prefix + 'fields' + index);
		display_data.hide();
		display_data.remove();
		data.remove();
		if(list_container.innerHTML == ''){
			$(listheaderid).fade();
			list_container.fade();
			// special case to check for and update disabled controls on the email form
			if(prefix == 'email'){
				if(!$('chkNewSpam').checked){
					oldspam_state('enable');
				}
			}
		}
		
		
	}
}

function edit_tech(prefix, itemindex, str_fields){
    
    // get data and put it in the form
    var arr_fields = str_fields.split(',');
	
	for(i=0;i<arr_fields.length;i++){
        $(arr_fields[i]).value = unescape($(arr_fields[i] + itemindex).value);
        
        if($(arr_fields[i]).tagName == 'SELECT' && $(arr_fields[i]).onchange)    
        {
            $(arr_fields[i]).onchange();
        }
    }
    $(prefix + '_editing').value = itemindex;
	
	$$('div.editing').invoke('removeClassName', 'editing');
	$(prefix + itemindex).addClassName('editing');
	
	if(!$(prefix + '_savelink').visible()){
		$(prefix + '_savelink').appear();
	}
    
	$(prefix + '_addlink').innerHTML = 'Add as New';
}

function update_tech(prefix, itemindex, str_fields, displayfieldid, displayvalue){
    var arr_fields = str_fields.split(',');
	if(!displayvalue){
		displayvalue = $(displayfieldid).value;
	}
	$(prefix + itemindex + '_link').innerHTML = displayvalue;
    for(i=0;i<arr_fields.length;i++){
        $(arr_fields[i] + itemindex).value = escape($F(arr_fields[i]));
		$(arr_fields[i]).value = '';
    }
    $(prefix + '_editing').value = '';
	
	$$('div.editing').invoke('removeClassName', 'editing');
	
	if($(prefix + '_savelink').visible()){
		$(prefix + '_savelink').fade();
	}
    
	$(prefix + '_addlink').innerHTML = $(prefix + "_add_text").value;
    $$('.other_container').invoke('hide');
	
}

function finalize_tech(prefix, fieldlist){
	var arr_finalfields = fieldlist.split(',');
	if(prefix == 'p2p'){
		addinfo_ip('p2p_ip', 'p2p_ip_address', '', '', 1);
	}
	if($(prefix + '_editing').value != ''){
		var editing_index = $(prefix + '_editing').value;
		
		for(i=0;i<arr_finalfields.length;i++){
			$(arr_finalfields[i] + editing_index).value = $(arr_finalfields[i]).value;
			$(arr_finalfields[i]).value = '';
		}
		$(prefix + '_editing').value = '';
	}
}

function show_group_form(showid, groupclass){
	$$('.'+groupclass).invoke('hide');
	if(showid){
		new Effect.SlideDown(showid);
	}
}

function gotostep(theformid, stepid){
	if(theformid){
		theform = $(theformid);
		if(stepid){
			var parent = $('step' + stepid);
			if(parent.hasClassName('complete')){
			
				switch(stepid){
					case '1':{
						theform.page.value = 'incidentType';
					}
					break;
					case '2':{
						theform.page.value = 'technologyType';
					}
					break;
					case '3':{
						theform.page.value = 'victimOrSuspectInfo';
					}
					break;
					case '4':{
						theform.page.value = 'otherAgencies';
					}
					break;
					case '5':{
						theform.page.value = 'contactInfo';
					}
					break;
					case '6':{
						theform.page.value = 'reportOverview';
					}
					break;
					default:{
						theform.page.value = '';
					}
				}
				if(theform.page.value != ''){
					theform.submit();
				}
			}
		}
	}
	
}

function set_required(fieldlist, fieldclass){
	if($('mainlist_message')){
		if($('mainlist_message').visible()){
			$('mainlist_message').fade();
		}
	}
	$$('.' + fieldclass).invoke('removeClassName', 'required');
	var arr_fields = fieldlist.split(',');
    for(i=0;i<arr_fields.length;i++){
		if($(arr_fields[i]).nodeName == 'SELECT'){
			$(arr_fields[i]).addClassName('validate-selection');
		}
		else{
			$(arr_fields[i]).addClassName('required');
		}
    }
}
var svid = '';
function getProvinces(country_id, uniqueid){
	if(uniqueid){
		svid = uniqueid;
		taint_country(uniqueid);
	}
	new Ajax.Request('XHR_get_country_states', {method: 'post', asynchronous: true, parameters: {id: country_id}, onSuccess: complete_getProvinces } );
}
function taint_country(uniqueid){
	eval('taintedcountry' + uniqueid + ' = 1;');
}

complete_getProvinces = function(req){
	var jsonObj = eval('(' + req.responseText + ')');
	if(jsonObj.error)
	{
		alert(jsonObj.error);
	}
	var provdd = $('state' + svid);
	provdd.options.length = 0;
	var ret = jsonObj.data;
	var size = ret.size();
	if(size > 0){
		for(i=0;i<size;i++){
            AddSelectOption(provdd, '{ LANG }' == 'en' ? ret[i].province_name : ret[i].province_name_fr, ret[i].province_id, false);
		}
	}
}

function AddSelectOption(selectObj, text, value, isSelected) 
{
    if (selectObj != null && selectObj.options != null)
    {
        selectObj.options[selectObj.options.length] = 
            new Option(text, value, false, isSelected);
    }
}

function cancel_form(formid){
	if(formid){
		var boxmsg = 'Are you sure you want to cancel (All of the data you entered will be lost)?'
		var currentlang = '{ LANG }';
		if(currentlang == 'fr'){
			boxmsg = 'Souhaitez-vous vraiment annuler? (Tous les renseignements que vous avez fournis seront supprimés)';
		}
		if(confirm(boxmsg)){
			$(formid).page.value = 'cancel';
			$(formid).submit();	
		}
	}
}

function switch_answer(theradio){
	var arr_techtypes = Array('','chat','email','im','p2p','website','other','newsgroup','ftp','bittorrent','computer_system');
	if(!theradio.checked){
		var hasdata = false;
		$$('input[type="text"]', 'textarea', 'select').each(function(item){
			if(item.value != ''){
				
				hasdata = true;
			}
		});
		if(!hasdata){ // check for any saved multiple items, since the above check doesn't count them
			var techindex = theradio.value;
			for(i=0;i<arr_techtypes.length;i++){
				if($(arr_techtypes[i] + '_fields')){
					if($(arr_techtypes[i] + '_fields').innerHTML != ''){
						hasdata = true;
					}
				}
			}
		}
		if(hasdata){
			if(confirm("Selecting a new item will remove the information you have entered.  Do you want to continue?")){
				retval = true;
				// clear any form data
				$$('input[type="text"]', 'textarea', 'select').each(function(item){
						item.value = '';
					}
				);
				// clear saved multiple item data
				for(i=0;i<arr_techtypes.length;i++){
					if($(arr_techtypes[i] + '_fields')){
						$(arr_techtypes[i] + '_fields').innerHTML = '';
						$(arr_techtypes[i] + '_list').fade();
						$(arr_techtypes[i] + '_list').innerHTML = '';
						$(arr_techtypes[i] + '_list_header').fade();
					}
				}
				theradio.click();
			}
		}
	}
	return false;
}

function switch_answerSV(theradio){
	// order matters here
	var arr_svdatadivs = Array('suspect_fieldsSX','suspect_fieldsS','victim_fieldsVX','victim_fieldsV');
	var arr_svlistdivs = Array('suspect_listSX','suspect_listS','victim_listVX','victim_listV');
	var arr_svlistheaderdivs = Array('suspect_list_headerSX','suspect_list_headerS','victim_list_headerVX','victim_list_headerV');
	
	// order doesn't matter here
	var arr_uniqueids = Array('S','SX','V','VX');
	var arr_taintedcountries = Array('taintedcountryS','taintedcountrySX','taintedcountryV','taintedcountryVX');
	if(!theradio.checked){
		var hasdata = false;
		var itemid;
		$$('input[type="text"]', 'textarea', 'select').each(function(item){
			if(item.value != ''){
				itemid = item.id;
				if(itemid.substr(0,7) == 'country'){ // check the country dropdown to see if it's the only field with a value and it's been touched.
					for(t=0;t<arr_taintedcountries.length;t++){
						if(eval(arr_taintedcountries[t]) == 1){
							hasdata = true;
						}
					}
				}
				else{
					hasdata = true;
				}
			}
		});
		if(!hasdata){ // check for any saved multiple items, since the above check doesn't count them
			for(i=0;i<arr_svdatadivs.length;i++){
				if($(arr_svdatadivs[i]).innerHTML != ''){
					hasdata = true;
				}
			}
			// check for the multi phone numbers, emails, usernames and ip's as well
			for(i=0;i<arr_uniqueids.length;i++){
				if($('datadiv' + arr_uniqueids[i]).innerHTML != ''){
					hasdata = true;
				}
			}
		}
		if(hasdata){
			if(theradio.value == 'both'){ // if we're switching to the "both" option, and we've got some data, just copy it into place instead of ditching it alltogether. Makes sense, yes?  I love lamp.
				// grab suspect info, pop it into play...
				/********************* TODO ****************
				 * This should be a function called once
				 * for victim and once for suspect, but everyone
				 * is all over my butt at the moment to deliver
				 * so it'll have to wait for the rush to be over ...
				 * meaning it'll probably never get done :)
				 * */
				$$('#suspect input[type="text"]', '#suspect textarea', '#suspect select').each(function(item){
					switch(item.name){
						case 'phoneS_main':{
							$('phoneSX_main').value = item.value;
						}
						break;
						case 'phoneS_sub':{
							$('phoneSX_sub').value = item.value;
						}
						break;
						case 'ip_addressS_o1':{
							$('ip_addressSX_o1').value = item.value;
						}
						break;
						case 'ip_addressS_o2':{
							$('ip_addressSX_o2').value = item.value;
						}
						break;
						case 'ip_addressS_o3':{
							$('ip_addressSX_o3').value = item.value;
						}
						break;
						case 'ip_addressS_o4':{
							$('ip_addressSX_o4').value = item.value;
						}
						break;
						case 'ip_addressS_port':{
							$('ip_addressSX_port').value = item.value;
						}
						break;
						default:{
							$(item.name + 'X').value = item.value;
						}
					}
					item.value = '';
				});
				
				/** now move all the "multiple" stuff over.  Not only additional suspects, but the multiple fields in each suspect too.
					This is probably going to make Brian's eyes bleed, but I think this is the easiest way to transfer all of this in
					one shot.  Well, at least in one operation per group.  I await the screams of agony when anyone else takes a look at this.
				
					I apologize in advance -- The CodeBreaker
				**/
				
				// grab any multiple suspect data
				var old_othersuspects = $('suspect_listS').innerHTML;
				if(old_othersuspects != ''){
				
					// The dirtyness ... do a string replace to assign the appropriate 'unique id' for the fields en masse
					var new_othersuspects = old_othersuspects.replace(/suspectS/g, "suspectSX");
					new_othersuspects = new_othersuspects.replace(/suspect_list_headerS/g, "suspect_list_headerSX");
					
					// write the adjusted string to the visible form
					$('suspect_listSX').innerHTML = new_othersuspects;
					
					// and cue the visuals
					$('suspect_list_headerSX').show();
					$('suspect_listSX').show();
				}
				
				// now the data...
				var old_othersuspects_data = $('suspect_fieldsS').innerHTML;
				if(old_othersuspects_data != ''){
					var new_othersuspects_data = old_othersuspects_data.replace(/S/g, "SX");
					$('suspect_fieldsSX').innerHTML = new_othersuspects_data;
				}
				
				
				// grab victim info, same as above
				
				$$('#victim input[type="text"]', '#victim textarea', '#victim select').each(function(item){
					switch(item.name){
						case 'phoneV_main':{
							$('phoneVX_main').value = item.value;
						}
						break;
						case 'phoneV_sub':{
							$('phoneVX_sub').value = item.value;
						}
						break;
						default:{
							$(item.name + 'X').value = item.value;
						}
					}
					item.value = '';
				});
				
				var old_othervictims = $('victim_listV').innerHTML;
				if(old_othervictims != ''){
					var new_othervictims = old_othervictims.replace(/victimV/g, "victimVX");
					new_othervictims = new_othervictims.replace(/victim_list_headerV/g, "victim_list_headerVX");
					$('victim_listVX').innerHTML = new_othervictims;
					$('victim_list_headerVX').show();
					$('victim_listVX').show();
				}
				var old_othervictims_data = $('victim_fieldsV').innerHTML;
				if(old_othervictims_data != ''){
					var new_othervictims_data = old_othervictims_data.replace(/V/g, "VX");
					$('victim_fieldsVX').innerHTML = new_othervictims_data;
				}
				
				
			}
			else{
			
				if(confirm("Selecting a new item will remove the information you have entered.  Do you want to continue?")){
					retval = true;
					// clear any form data
					$$('input[type="text"]', 'textarea', 'select').each(function(item){
							item.value = '';
						}
					);
					// clear saved multiple item data
					for(i=0;i<arr_svdatadivs.length;i++){
						$(arr_svdatadivs[i]).innerHTML = '';
						$(arr_svlistdivs[i]).fade();
						$(arr_svlistdivs[i]).innerHTML = '';
						$(arr_svlistheaderdivs[i]).fade();
					}
					
					// clear any of the multi data per item .. items?  Phone, ip addies, etc.  What would you call them?
					for(i=0;i<arr_uniqueids.length;i++){
						if($('moreip_address' + arr_uniqueids[i])){ // only suspect has IP, so dont' wanna barf when doing victim forms
							$('moreip_address' + arr_uniqueids[i]).innerHTML = '';
							$('moreip_address' + arr_uniqueids[i]).hide();
						}
						$('morephone' + arr_uniqueids[i]).innerHTML = '';
						$('morephone' + arr_uniqueids[i]).hide();
						$('moreemail' + arr_uniqueids[i]).innerHTML = '';
						$('moreemail' + arr_uniqueids[i]).hide();
						$('moreusername' + arr_uniqueids[i]).innerHTML = '';
						$('moreusername' + arr_uniqueids[i]).hide();
						
						$('datadiv' + arr_uniqueids[i]).innerHTML = '';
					}
					
					theradio.click();
				}
			}
		}
	}
	return false;
}

function set_defaults(thecontrol){
	if(thecontrol){
		var default_val;
		var fields = new Array();
		var uid;
		switch(thecontrol.value){
			case "suspect":{
				uid = 'S';
				fields = ['username','email','ip_address'];
				assign_defaults(uid, fields);
			}
			break;
			case "child":{
				uid = 'V';
				fields = ['username','email'];
				assign_defaults(uid, fields);
			}
			break;
			case "both":{
				uid = 'SX';
				fields = ['username','email','ip_address'];
				assign_defaults(uid, fields);
				
				uid = 'VX';
				fields = ['username','email'];
				assign_defaults(uid, fields);
			}
			break;
			default:{
				uid = '';
			}
		}
	}
}

function assign_defaults(uid, fields){
	if(uid){
		if(uid != ''){
			for(i=0;i<fields.length;i++){
				default_val = $('default_' + fields[i] + uid).value;
				if(default_val != ''){
					$(fields[i] + uid).value = default_val;
					if(fields[i] == 'ip_address'){
						expand_extrainfo(fields[i] + uid, fields[i] + uid, fields[i] + uid, 'moreip_address' + uid, 'datadiv' + uid,':');
					}
				}
				$('default_' + fields[i] + uid).value = '';
			}
		}
	}
}

specify_other = function(elem,val)
{
    
    //if(elem.options[elem.selectedIndex].value == val)
    if($F(elem) == val)
    {
        elem.next('.other_container').appear();
    }
    else
    {
        elem.next('.other_container').hide();
    }

}

show_age = function(uniqid)
{
    var age_div = $('age_div'+uniqid);
    
    age_div.toggle();
    
   
    
}

hide_age = function(uniqid)
{
    age_div = $('age_div'+uniqid);
    age_div.hide();
    
}

function oldspam_state(mode){
    if(mode){
        switch(mode){
            case 'enable':{
                enable_form(1, 'oldspam_container');
                $('newspam_label').addClassName('disabled');
                $('email_timezone_oldspam').addClassName('required');
                $('email_date_oldspam').addClassName('required');
            }
            break;
            case 'disable':{
                enable_form(0, 'oldspam_container');
                $('newspam_label').removeClassName('disabled');
                $('email_timezone_oldspam').removeClassName('required');
                $('email_date_oldspam').removeClassName('required');
            }
            break;
            default:{
                
            }
        }
    }
}

function enable_form(val, parentdiv){
    if(parentdiv){
        if(val == 1){
            $(parentdiv).select('label').invoke('removeClassName', 'disabled');
            $(parentdiv).select('h2').invoke('removeClassName', 'disabled');
            $(parentdiv).select('[type="text"]', 'textarea', '[type="button"]', '[type="radio"]', 'select').invoke('enable');
            $(parentdiv).select('span').invoke('removeClassName', 'disabled');
        }
        else{
            $(parentdiv).select('label').invoke('addClassName', 'disabled');
            $(parentdiv).select('h2').invoke('addClassName', 'disabled');
            $(parentdiv).select('[type="text"]', 'textarea', '[type="button"]', '[type="radio"]', 'select').invoke('disable');
            $(parentdiv).select('span').invoke('addClassName', 'disabled');
        }
    }
}

function set_newspam(mode, control, datadivid, listdivid, str_fields){
    var getout = 0;
    var datadiv = $(datadivid);
    var listdiv = $(listdivid);
    if(mode == 1){
        if(control){
            if(!control.checked){
                // check for new spam that's been entered/added.  if so, alert them
               
               if(datadiv.innerHTML != ''){
                    if(confirm("{ SELECT_EMAIL_REMOVE_EMAIL }")){
                        datadiv.select('div').invoke('remove');
                        listdiv.select('div').invoke('remove');
                        listdiv.fade();
                        $('email_list_header').fade();
                    }
                    else{
                        getout = 1;
                        control.checked = true;
                    }
                }
				else{
					// check if any data has been entered in the fields.  If so prompt
					var enteredcontent = 0;
					var arr_fields = str_fields.split(',');
					for(i=0;i<arr_fields.length;i++){
						if($(arr_fields[i]).value != ''){
							enteredcontent = 1;
						}
					}
					
					if(enteredcontent == 1){
						if(confirm("{ SELECT_EMAIL_REMOVE_INFO }")){
							for(i=0;i<arr_fields.length;i++){
								$(arr_fields[i]).value = '';
							}
						}
						else{
							getout = 1;
							control.checked = true;
						}
					}
					
				}
                if(getout == 0){
                    if($('newspam').visible()){
                        new Effect.SlideUp('newspam');
                    }
                    oldspam_state('enable');
                    newEmail = 0;
                }
            }
            else{
                var hasoldspam = false;
				if(datadiv){ // getting an error on load as this seems to fire before the dom is loaded, so just see if the div exists first.
					if(datadiv.innerHTML != ''){
						var form = $('reportForm');
						var emailids = form.getInputs('hidden', 'email_id');
						emailids.each( function(item) {
							if((item.value != '') && (item.value != '0')){
								hasoldspam = true;
							}
						});
						
						if(hasoldspam){
							if(confirm("{ NEW_INFO_REMOVE_SELECTED }")){
								datadiv.select('div').invoke('remove');
								listdiv.select('div').invoke('remove');
								listdiv.fade();
								$('email_list_header').fade();
							}
							else{
								getout = 1;
								control.checked = false;
							}
						}
					}
				}
                
                if(getout == 0){
                    setspam(null);
                    newEmail = 1;
                    oldspam_state('disable');
                    new Effect.SlideDown('newspam');
                    var spamlist = $('reportForm').elements['spam_id'];
                    var spamlist_length = spamlist.length;
                    for(var i = 0; i < spamlist_length; i++){
                        spamlist[i].checked = false;
                    }
                    
                    // if there's a date/timezone in the list section, pop it into the newspam form fields
                    if($('email_date_oldspam').value != ''){
                        $('email_date').value = $('email_date_oldspam').value;
                        $('email_date_oldspam').value = '';
                    }
                    if($F('email_timezone_oldspam') != ''){
                        $('email_timezone').value = $F('email_timezone_oldspam');
                        $('email_timezone_oldspam').clear();
                    }
                }
            }
        }
        
    }
    return false;
}

function set_displayvalue(uniqueid, genericvalue){
	var displayvalue;
	displayvalue = $('first_name' + uniqueid).value + ' ' + $('last_name' + uniqueid).value;
    displayvalue = displayvalue.replace(/^\s+|\s+$/g, ''); // regex for trimming whitespace at the start and end of the string
	if(displayvalue == ''){
		if($('username' + uniqueid).value != ''){
			 var usernames = $('username' + uniqueid).value;
			 var arrusernames = usernames.split(',');
			 displayvalue = arrusernames[0];
		}
		else{
			if($('email' + uniqueid).value != ''){
				var emails = $('email' + uniqueid).value;
				var arremails = emails.split(',');
				displayvalue = arremails[0];
			}
		}
	}
	 
	if(displayvalue == ''){
		displayvalue = genericvalue + ' ' + techCnt;
	}
	
	return displayvalue;
}

function savesession(){
	/** extrememly dirty way of completing an "edit" of an existing item before sending the data.  Prevents a duplicate from being sent **/
	var arr_techtypes = new Array('','chat','email','im','p2p','website','other','newsgroup','ftp','bittorrent','computer_system','suspectS','suspectSX','victimV','victimVX');
	for(i=0;i<arr_techtypes.length;i++){
		if($(arr_techtypes[i] + '_editing')){
			if($(arr_techtypes[i] + '_editing').value != ''){
				eval('update_' + arr_techtypes[i] + '();');
				//console.log("update script: ", 'update_' + arr_techtypes[i] + '();');
			}
		}
	}
	var theform = $('reportForm');
	var formdata = theform.serialize(true);
	new Ajax.Request('XHR_save_report_step', {method: 'post', asynchronous: false, parameters: formdata} );
}

var validateNoURL = Class.create({
    initialize: function(options)
    {
        this.options = Object.extend({
            selector: '.validate-no-url',
            form    : 'frm1'
        },options || {});
        this.form = $(this.options.form);
        
        this.elements = this.form.select(this.options.selector);
        this.elements.each(function(elem){
            
            Event.observe(elem,'keyup',  this.validate_no_url.bindAsEventListener(this));
            Event.observe(elem,'blur',      this.validate_no_url.bindAsEventListener(this));
        }.bind(this));
    },
    validate_no_url: function(event)
    {
        var elem = event.element();
        var error = false;
        
        m = elem.value.match(/https?:\S*/i);
        if(m)
        {
            elem.value = elem.value.replace(/https?:\S*/ig,'');
            error = true;
        }
        
        m = elem.value.match(/www\..*?/i)
        if(m){
            elem.value = elem.value.replace(/www\.\S*/gi,'');
            error = true;
        }
        
        if(error)
        {
            alert("{ NO_URL_PROVIDE_ADDITIONAL }");
        }
        
        
    }
    
});

allBlank = function(form,divclass)
{
    form = $(form); 
    var all_blank = false;  
    //first find the technology we are in
    var techDiv = form.select('.'+divclass).find(function(elem){
        return elem.style.display != 'none';
    });
    if(techDiv)
    {
        var data_list = techDiv.select('.data_list').first();
        if(data_list && data_list.style.display != 'none') //we have a data list
        {
            all_blank = true;
            
            techDiv.select('.validate-all-or-none').each(function(elem){
                
                if(elem.value != '')
                {
                    all_blank = false;
                }
            
            });
        }
    
    }
    return all_blank;
}


String.prototype.htmlEntities = function () {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}; 
