function closeWizard(){
    showComboboxes();
    $('wizard').style.display='none';
    $('wizard_overlay').style.display='none';
    $('wizard').innerHTML='';
}
function init_wizard(size) {   
    eval('var size = [' + size + '];');       
  //alert(size[1]);
    var obj = $S('wizard');
    obj.display = 'block';
    calculate_wizard_overlay_size();   
    if (size[0]<1) {        
        obj.width=size[0]*document.body.clientWidth;        
        obj.left=(document.body.clientWidth - size[0]*document.body.clientWidth)/2;    
    }    
    else {        
        obj.width=size[0];        
        obj.left=(document.body.clientWidth - size[0])/2;    
    }    
    if (size[1]<1) {
        obj.height=size[1]*document.body.clientHeight;
        obj.top=(document.body.clientHeight - size[1]*document.body.clientHeight)/2 + f_scrollTop();
    }    
    else {        
        obj.height=size[1];
        obj.top=(document.body.clientHeight  - size[1])/2 + f_scrollTop();    
    }
}



//parameter 1 - action - the name of the action that we call parameterized in struts-config.xml
//parameter 2 - target- the id of the div tag that we want to add the content of the server response
//parameter 3 - form - the form object that we submiting 

function close_wizard(target){
    return ($S('wizard').display == 'block' && target != 'wizard');
}
function _wizard(action,form) {
    hideComboboxes();
    $S('wizard_overlay').display='block';
    if(_wizard.arguments.length == 4){
	apost(action,'wizard',form,_wizard.arguments[2],_wizard.arguments[3]);
    }else if(_wizard.arguments.length == 6){
	apost(action,'wizard',form,_wizard.arguments[2],_wizard.arguments[3],_wizard.arguments[4],_wizard.arguments[5]);
    }else if(_wizard.arguments.length == 8){
	apost(action,'wizard',form,_wizard.arguments[2],_wizard.arguments[3],_wizard.arguments[4],_wizard.arguments[5],_wizard.arguments[6],_wizard.arguments[7]);
    }else if(_wizard.arguments.length == 10){
	apost(action,'wizard',form,_wizard.arguments[2],_wizard.arguments[3],_wizard.arguments[4],_wizard.arguments[5],_wizard.arguments[6],_wizard.arguments[7],_wizard.arguments[8],_wizard.arguments[9]);
    }else if(_wizard.arguments.length == 12){
	apost(action,'wizard',form,_wizard.arguments[2],_wizard.arguments[3],_wizard.arguments[4],_wizard.arguments[5],_wizard.arguments[6],_wizard.arguments[7],_wizard.arguments[8],_wizard.arguments[9],_wizard.arguments[10],_wizard.arguments[11]);
    }else if(_wizard.arguments.length == 14){
	apost(action,'wizard',form,_wizard.arguments[2],_wizard.arguments[3],_wizard.arguments[4],_wizard.arguments[5],_wizard.arguments[6],_wizard.arguments[7],_wizard.arguments[8],_wizard.arguments[9],_wizard.arguments[10],_wizard.arguments[11],_wizard.arguments[12],_wizard.arguments[13]);
    }else{         
	apost(action,'wizard',form);
    }
}

//sends the client's request to the server 
//parameter 1 - action - the name of the action that we call parameterized in struts-config.xml
//parameter 2 - target- the id of the div tag that we want to add the content of the server response
//parameter 3 - form - the form object that we submiting 

function apost(){
    try {
		var action = apost.arguments[0];
		var target = apost.arguments[1];
		var form = apost.arguments[2];
		var wizard_size = '';
		if(apost.arguments.length > 3){
		    for(var i = 3; i < apost.arguments.length; i+=2){
                        var element = new_element(form,apost.arguments[i] );
			element.value=apost.arguments[i+1];
                        
			if(target == 'wizard' && apost.arguments[i] == 'size'){
			    wizard_size = apost.arguments[i+1];
			}
		    }
		}
                
		document.body.style.cursor = 'wait';
		
		var URL;
		if(action.indexOf('.do?') == -1){
		    URL = action + '.do';
		}else{
		    URL = action;
		}
		if (!post) post = '';
		if (!target) target = 'main';
		var obj = $(target);
		var post;
		for (i = 0; i < form.elements.length; i++) {
			if (form.elements[i].type == "checkbox") {
				if (form.elements[i].checked) post += "&" + form.elements[i].name + "=" + convertSymbols(form.elements[i].value);
			}
			else if (form.elements[i].type == "radio") {
				if (form.elements[i].checked) post += "&" + form.elements[i].name + "=" + convertSymbols(form.elements[i].value);
			}
			else
				post += "&" + form.elements[i].name + "=" + convertSymbols(form.elements[i].value);
				    
		}

		if(target == 'wizard' && (wizard_size || form.size)) {   
		    try { 
			init_wizard(form.size.value);
			} 
		    catch (err) {init_wizard(wizard_size);}
		}       
		var ajaxOpts = {
			method: 'post',
			postBody: post,
			onSuccess: function(msg) {
try{
                                                                //var obj = '';
								document.body.style.cursor = "default";
								var hasExceptions = msg.responseText.indexOf('new[*]exceptions[*]occurs') != -1;
								if(close_wizard(target) && 
									 hasExceptions){
								    obj = $('wizard');
								    target = 'wizard';	
								}
								var hasErrors = msg.responseText.indexOf('id=\"error[*]\"') != -1;
								if(target == 'wizard' && msg.responseText.indexOf('id=\"error[*]\"') != -1){
								    var h = $('height');
								    var a = msg.responseText.split('error[*]');
								    var index = $S('wizard').height.indexOf('px');
								    $S('wizard').height = parseInt(h.value) + (a.length-1)*20 + 12;
								}
                                try{ 
								if(form._eval0 && form._eval0.value != ''){
									var addtnlStr = 'var  ';
									if(form._eval0.value.indexOf('hasErrors') != -1){
										addtnlStr += 'hasErrors = ' + hasErrors + ';';
									}else if(form._eval0.value.indexOf('hasExceptions') != -1){
										addtnlStr += 'hasExceptions = ' + hasExceptions + ';';
									}else if(form._eval0.value.indexOf('hasSTag') != -1){
										addtnlStr += 'hasSTag = ' + (msg.responseText.indexOf('</s>') != -1) + ';';
									}else{
										addtnlStr = '';
									}
									
									if(form._eval0.value.indexOf('showAddressFunc') != -1){
										
										var addressDisplay = msg.responseText.substring(msg.responseText.indexOf('<displayUpdate>')+15,msg.responseText.lastIndexOf('<displayUpdate>'));
										addtnlStr += 'showAddress(\''+addressDisplay+'\');';
										form._eval0.value = '';
										
									}
									
									window.eval(addtnlStr + form._eval0.value);
								}
                                }catch(err){}	

                                var keepWizardOpenedVar = 'no';
                                if(form.keepWizardOpened){
                                	keepWizardOpenedVar = form.keepWizardOpened.value;
                                }

								if(target != 'wizard' && keepWizardOpenedVar == 'no'){
								    $S('wizard_overlay').display='none';
								    var wizardObj = $('wizard');
								    wizardObj.style.display='none';
								    wizardObj.innerHTML = '';
                                                                    showComboboxes();
								}
                                if(obj != null){
                                	obj.innerHTML = msg.responseText;
                                }
                                
                                if(form._eval1 && form._eval1.value != ''){
                                	window.eval(form._eval1.value);
                                }

	}catch(err){
            //alert('onSuccess ' + err);
        }							
							},
			onFailure: function(msg) {
								document.body.style.cursor = "default";
								obj.innerHTML = msg.responseText;
								
							}
		};
		
		new Ajax.Request( URL, ajaxOpts );
		
	} 
	catch(err) {alert('apost2 ' + err);}

	
    }


function _submit(action,form,name,value){
	var element = new_element(form,name );
			element.value=value;
	if (action) form.action = get_action(action);
	form.submit();
}
//the function should be called atleast with 3 parameters:
//action
//name - a name of the property that we want to sent to the action
//value - the value of the property
//we can add additional properties. for each new property we have to add name and value parameters
function _sv(){
    var action = _sv.arguments[0];
    var name = _sv.arguments[1];
    var value = _sv.arguments[2];

    

    var element;
    if(name){
	element =  newElement(name, name);
    }else{
	element = newElement("id", "id");
    }
    element.value = value;
    
    if(_sv.arguments.length >= 5){
	var element2;
	var name2 = _sv.arguments[3];
	var value2 = _sv.arguments[4];
	if(name2){
	    element2 =  newElement(name2, name2);
	}else{
	    element2 = newElement("id", "id");
	}
	element2.value = value2;
    }
    if(_sv.arguments.length >= 7){
	var element3;
	var name3 = _sv.arguments[5];
	var value3 = _sv.arguments[6];
	if(name3){
	    element3 =  newElement(name3, name3);
	}else{
	    element3 = newElement("id", "id");
	}
	element3.value = value3;
    }
    _action(action);
}
function _action(action) {
    
    document.page.action = get_action(action);
    document.page.submit();
}
///////////////////////////////////////////////////
//the function should be called atleast with 3 parameters:
//action
//form - the name of the form - ex: MainForm 
//name - a name of the property that we want to sent to the action
//value - the value of the property
//we can add additional properties. for each new property we have to add name and value parameters
function _sv2(){
    var action = _sv2.arguments[0];
    var form = $(_sv2.arguments[1]);
    var name = _sv2.arguments[2];
    var value = _sv2.arguments[3];

 

    var element;
    	element =  new_element(form, name);
    
    element.value = value;
    
    if(_sv2.arguments.length >= 6){
	var name2 = _sv2.arguments[4];
	var value2 = _sv2.arguments[5];
	var element2 =  new_element(form, name2);
	element2.value = value2;
    }
 if(_sv2.arguments.length >= 8){
	var element3;
	var name3 = _sv2.arguments[6];
	var value3 = _sv2.arguments[7];
	element3 =  new_element(form, name3);
	element3.value = value3;
    }
    _action2(action,form);
closeWizard();
}
function _action2(action,form) {
    try{
        if(action == ''){
            action = form.action;
        }
        form.action = get_action(action);
    }catch(err){
        //alert(err);
    }
    form.submit();
}

///////////////////////////////////////////////////
function get_action(action){
    var index = action.indexOf('.do');
    var suffix = "";

    if(index == -1){
        suffix = ".do";
    }
    return action + suffix;
}
function newElement(id, name) {
	var element;
	try {

		 	element = document.createElement('input');
			element.setAttribute('type','hidden');
			element.setAttribute('id',"_" + id);
			element.setAttribute('name',name);
			element.setAttribute('value','0');
			document.page.appendChild(element);
		
	}
	catch (err) {}
	
	return element;
}
function new_element(form, name) {
	try {
	    var element;
	    if(form[name] == undefined){
	    	 	element = document.createElement('input');
			element.setAttribute('type','hidden');
			element.setAttribute('name',name);
			element.setAttribute('value','0');
			form.appendChild(element);
	}else{
	    element = form[name];
	}
	}
	catch (err) {alert('new_element ' + err);}
	return element;
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

//the method returns the stylesheet object of the element with ident id
function $S(id){
    return $(id).style;
}
function calculate_wizard_overlay_size(){
    var obj2 = $S('wizard_overlay');
    
    if(obj2.display != 'none'){
	obj2.height=document.body.scrollHeight;
	obj2.width=document.body.scrollWidth;
    }
    calculateAditionalColumn();
}
function calculateAditionalColumn(){
    try{
    var screenWidth = document.body.scrollWidth;
    var widthColumnsMain = parseInt($('startColumn').width);
    for(var i = 0; i < 100; i++){
        var td = $('mainTab_'+i);
        var tdSpace = $('mainTabSpace_'+i);
        
        if(!td){   
            break;
        }
        widthColumnsMain += parseInt(td.width);
        widthColumnsMain += parseInt(tdSpace.width);
    }

    $('addtnlColumnMain').width = screenWidth - widthColumnsMain;
    if($('startSubColumn')){
        var widthColumnsSub = parseInt($('startSubColumn').width);
        for(var i = 0; i < 100; i++){
            var td = $('subTab_'+i);
            var tdSpace = $('subTabSpace_'+i);
            if(!td){   
                break;
            }
            widthColumnsSub += parseInt(td.width);
            widthColumnsSub += parseInt(tdSpace.width);
        }
        $('addtnlColumnSub').width = screenWidth - widthColumnsSub;
    }

    if($('startSubSubColumn')){
        var widthColumnsSubSub = parseInt($('startSubSubColumn').width);
 
        for(var i = 0; i < 100; i++){
            var td = $('subSubTab_'+i);
            var tdSpace = $('subSubTabSpace_'+i);
            if(!td){   
                break;
            }
               
            widthColumnsSubSub += parseInt(td.width);
            widthColumnsSubSub += parseInt(tdSpace.width);
        }
        if((screenWidth - widthColumnsSubSub) > 0){
            $('addtnlColumnSubSub').width = screenWidth - widthColumnsSubSub;
        }else{
            $('addtnlColumnSubSub').width = 1;
        }
    }

    if(document.body.width <= 1000){
        document.body.width = '1000';
        $('mainTable').width = '99%';
    }else{
        $('mainTable').width = '99%';
    }
    }catch(err){
        document.body.width = '2000';
        $('mainTable').width = '99%';
    }
    
//alert($('addtnlColumnSub').width);
}
function keyPressHandler(e) {
      var kC  = (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
      var Esc = (window.event) ?   
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
      //if(kC==Esc && $S('wizard_overlay'))
         //alert("Esc pressed")
}
function convertSymbols(value){
    if(!value){
        return value;
    }
        var symbols = '!@#$%^&*()_-+=?><,./~`';
        for(var i = 0; i < value.length; i++){
            if(symbols.indexOf(value.substring(i,i+1))!=-1){
		var tmpValue = value.substring(i+1);
		//alert(value.substring(i,i+1));
                value = value.substring(0,i)+'%'+byte2Hex(value.charCodeAt(i))+tmpValue;
		i = value.lastIndexOf(tmpValue);
            }
        }
	return value;
    }
function byte2Hex(n){
        var nybHexString = "0123456789ABCDEF";
        return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
}

function selectFieldText(text_field)
{
    text_field.focus();
    text_field.select();
}
///////////////////////////////////////////////////

function ajaxUpload(form, url_action, return_id, message_id, html_show_loading, html_error_http){
	try{
	document.body.style.cursor = 'wait';
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","micox-temp");
	iframe.setAttribute("name","micox-temp");
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","0");
	iframe.setAttribute("style","width: 0; height: 0; border: none;");
	var action = form.action;
	var post = form.post;
	var enctype = form.enctype;
	var encoding = form.encoding;
 
	form.parentNode.appendChild(iframe);
	window.frames['micox-temp'].name= "micox-temp";
 
	var carregou = function() { 
            try{
                        document.body.style.cursor = 'default';
			removeEvent( $('micox-temp'), "load", carregou);
			$(message_id).innerHTML = '';
			$('micox-temp').src = "javascript: " + "window.parent.$('" + return_id + "').innerHTML = document.body.innerHTML; void(0); ";

			window.parent.page.action = action;
			window.parent.page.post = post;
			window.parent.page.enctype = enctype;
                        window.parent.page.encoding = encoding;

			try{
			//remove($('micox-temp'));
		    }catch(err){alert(err);}
		}catch(err){
                    form.action = action;
                    form.post = post;
                    form.enctype = enctype;
                    form.encoding = encoding;
		    try{
			//remove($('micox-temp'));
		    }catch(err){alert(err);}
                }
            document.body.style.cursor = 'default';
            //alert(document.body.innerHTML.indexOf('error[*]') != -1);
        }
		
	addEvent( $('micox-temp'), "load", carregou)
	
	form = typeof(form)=="string"?$(form):form;
	form.setAttribute("target","micox-temp");
	form.setAttribute("action",url_action);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	form.submit();
 
	if(html_show_loading.length > 0) $(message_id).innerHTML = html_show_loading;
	return false;
	}catch(err){alert(err);}
	
}
function addEvent(obj, evType, fn){// elcio.com.br/crossbrowser
	if (obj.addEventListener) obj.addEventListener(evType, fn, true)
	if (obj.attachEvent) obj.attachEvent("on"+evType, fn)
}
function removeEvent( obj, type, fn ) {
	if ( obj.detachEvent )
		obj.detachEvent( 'on'+type, fn );
	else
		obj.removeEventListener( type, fn, false );
} 
function remove(quem){
	quem.parentNode.removeChild(quem);
}

///////////////////////////////////////////////////////////
function pause(numberMillis) {
 var now = new Date();
 var exitTime = now.getTime() + numberMillis;
  while (true) {
   now = new Date();
   if (now.getTime() > exitTime)
    return;
   }
  }


function hideComboboxes(){
if(window.external &&
	typeof window.XMLHttpRequest == "undefined"){
try{
    var formsLength = document.forms.length;
    for(var i = 0; i < formsLength; i++){
        var form = document.forms[i];
        var elementsLength = form.elements.length;

        for(var j = 0; j < elementsLength; j++){
            var element = form.elements[j];
            if(element.type.indexOf('select-') != -1){
                element.style.display = 'none';

            }
        }
        
    }
}catch(err){alert(err);}
}
}

function showComboboxes(){
if(window.external &&
	typeof window.XMLHttpRequest == "undefined"){
try{
    var formsLength = document.forms.length;
    for(var i = 0; i < formsLength; i++){
        var form = document.forms[i];
        var elementsLength = form.elements.length;

        for(var j = 0; j < elementsLength; j++){
            var element = form.elements[j];
            if(element.type.indexOf('select-') != -1 && element.style.display == 'none'){
                element.style.display = '';

            }
        }
        
    }
}catch(err){alert(err);}
}
}
/////////////////////////////////////////////////////////////////////////
function manageCompanyNameField(accountType, personalType, businessType, form){
    if(accountType == personalType){
        $S('company_name').display='none';
        form.companyName.value='';
        $('showCompanyName').value = personalType;
    }else{
        $('company_name').className = '';
        $S('company_name').display='';
        $('showCompanyName').value = businessType;
    }
}

function saveUpdatedDetails(oldAccountType, message1, message2){
    var newAccountType = $('showCompanyName').value;
    if(oldAccountType == newAccountType || confirm(message1+'\n'+message2)){
        apost('userProfile','mngUsr',document.UserForm, 'actionForm','Submit');
    }
}
function checkFeedbackSubject(val, form){
    if(val == 'other'){
        $S('subject_other').display='';

        var index = $S('wizard').height.indexOf('px');
        var high = $S('wizard').height;
	$S('wizard').height = parseInt(high.substring(0,index))+30;
    }else{
        $S('subject_other').display='none';
        $S('wizard').height = parseInt($('height').value);
    }
}
function checkValue(value, form){
    if(value.length > 0){
        form.distance.disabled=false;
        form.unit[0].disabled=false;
        form.unit[1].disabled=false;
    }else{
        form.distance.disabled=true;
        form.unit[0].disabled=true;
        form.unit[1].disabled=true;
    }
}

function scrollToTop(scrollPixels){
	var goto_top_type;
	var pixels = 0;
	if(scrollPixels){
		pixels = scrollPixels;
	}
	if (document.documentElement && document.documentElement.scrollTop)
		goto_top_type = 1;
	else if (document.body && document.body.scrollTop)
		goto_top_type = 2;
	else
		goto_top_type = 0;
	if (goto_top_type == 1)
		document.documentElement.scrollTop = pixels;
	else
		document.body.scrollTop = pixels;
}

function handleKeyPressed(keyCode){
	if(keyCode == 27){
		if($('not_close_esc')){
			return false;
		}
		closeWizard();
	}
}