var EMAIL_RESOURCE_ADDRESS = "/xmlresp?app=GeneraliWWW&pname=";
var DEFAULT_SEND_PORTLET = "AgentFormAsync";
var EMAIL_NO_AJAX_ERROR = "Twoja przegladarka nie pozwala wyslac maila. Uzycie nowszej przgladarki moze rozwiazac ten problem";
var EMAIL_CONNECTION_ERROR = "Blad serwera lub polaczenia. Sprawdz, czy inne strony z tego serwera sa dostepne.";
var EMAIL_NULL_SERVER_RESP = "Blad. Serwer nie przyslal odpowiedzi. \nSkontaktuj sie z administratorem zdalnego systemu";


var fields = new Array();
fields['infonameAF']=false;
fields['infosurnameAF']=false;
fields['infophone_numberAF']=false;
fields['infoemailAF']=false;
fields['infozipcodeAF']=false;
fields['infocityAF']=false;
var skin = "";

    
    function setSkin(s){
        skin=s;
    }   
    
    function setValid(id) {
        document.getElementById('info'+id).src = skin+'/img/validMark.gif';
        fields['info'+id] = true;
    }    
    function setInvalid(id) {
        document.getElementById('info'+id).src = skin+'/img/invalidMark.jpg';
        fields['info'+id] = false;
    }   
    
    function validateLength(id) {
         var value = document.getElementById(id).value;
         if(value && value != null && value != ''){
             return setValid(id);
         }
         return setInvalid(id);
    }
    
    function validatePhone(id) {
        var value = document.getElementById(id).value;
        var PATTERN = /^\d{8,9}$/;
        if(value && value!=null && PATTERN.test(value)) {
            return setValid(id);
        }
        
        return setInvalid(id);
        alert(value);
    }
    
    function validateZipCode(id) {
        var value = document.getElementById(id).value;
        if(value && value != null && value != ''){
            if(value.match(/^\d{2}[-]\d{3,3}$/)){
                return setValid(id);                
            }
        }
        return setInvalid(id);
    }
    
    function validateEmail(id) {
        var value = document.getElementById(id).value;
        var PATTERN = /^[a-zA-Z0-9]+(([\.\-_][a-zA-Z0-9])*[a-zA-Z0-9]*)*\@[a-zA-Z0-9]((\.)?[a-zA-Z0-9\-]*[a-zA-Z0-9])*(\.[a-zA-Z0-9]{2,4})+$/;
        if(value && value != null && PATTERN.test(value)) {
            return setValid(id);
        }
        return setInvalid(id);
    }        
    
    function submitAgentForm(customSendPortlet) { 
       var flag = 0;
       var i = 0;
       var firstCol = 0, secondColumn = 0;       
       
       for ( keyVar in fields ) {
           if( fields[keyVar] != true) {
               showMessage(keyVar);
               flag = 1;
               if(i<3){
            	   firstCol++;
               }else{
            	   secondColumn++;
               }
           }
           else {
               hideMessage(keyVar);
           }
           i++;
       }       
       if( flag == 0 ) {
           sendEmail(customSendPortlet);
       
           //return document.getElementById('agentForm').submit();
       } else {    	   
    	   var _background =  document.getElementById('AgentFormDiv');    	   
    	   if(_background){    		   
    		   var max = firstCol;
    		   if(max < secondColumn){
    			   max = secondColumn-1;
    		   }    	   
    		   
    		   if(182 + max*16 <= 182+3*16){    			   
    			   _background.style.height = (182 + max*16) + 'px';
    		   }
    	   }
       }
       return;
    }
    
    function showHint( id ) {
        var _IFRAME = document.getElementById( id + '_IFRAME' );
        var _DIV = document.getElementById(id + '_HINT' );
        var _IMG = document.getElementById( id + '_IMG_HINT' );
        _DIV.style.display='';
        if(_IMG != null){
        //bylo coords.y+5 i coords.x+5
             var coords = getElementCoords( _IMG );
            _DIV.style.top = (coords.y + 15) + "px";
            _DIV.style.left = (coords.x + coords.w + 3) + "px";
            _IFRAME.style.top = (coords.y + 15) + "px";
            _IFRAME.style.left = (coords.x + coords.w + 3) + "px";
            _IFRAME.style.height = (_DIV.offsetHeight) + "px";
        }
        var coords2 = getElementCoords( _DIV );
       
        _IFRAME.style.display='';
    }
       
    function hideHint( id ) {
        var _DIV = document.getElementById( id + '_HINT' );
        var _IFRAME = document.getElementById( id + '_IFRAME' );
        _DIV.style.display="none";
        _IFRAME.style.display="none";
    }
    
    function getElementCoords( element ) {
        var coords = {x: 0, y: 0, h: 0, w: 0};
        coords.w = element.offsetWidth;
        coords.h = element.offsetHeight;
        while ( element ) {
            if ( element != null ) {
                coords.x += element.offsetLeft;
                coords.y += element.offsetTop;
                element = element.offsetParent;
            }
        }
        return coords;
    }
    
    function showMessage(questionFormName) {    
       var _output = document.getElementById(questionFormName + '_ERR');    
       if ( _output ) {
           _output.style.display = '';
       }    
    }
    
    function hideMessage(questionFormName) {    
       var _output = document.getElementById(questionFormName + '_ERR');    
       if ( _output ) {
           _output.style.display = 'none';
       }    
    }    
    
    
    
    
function sendEmail(customSendPortlet) {
    var agentElem = document.getElementById('agentSelect');
    
    var specId  = agentElem.options[agentElem.selectedIndex].value
    var name    = document.getElementById('nameAF').value;
    var surname = document.getElementById('surnameAF').value;
    var phone   = document.getElementById('phone_numberAF').value;
    var email   = document.getElementById('emailAF').value;
    var zipcode = document.getElementById('zipcodeAF').value;
    var city    = document.getElementById('cityAF').value;
    
    var questionInput  = document.getElementById('questionAF');
    if(questionInput != null) {
        var question = questionInput.value;
    }
    var configIdInput  = document.getElementById('CONFIG_ID');
    var configId = "";
    if(configIdInput != null) {
        configId = configIdInput.value;
    }

    var xmlHttp;
    try {
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert(EMAIL_NO_AJAX_ERROR);
                return false;
            }
        }
    }
    
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
        	// warunek z 3xx dodany na potrzeby omniprofit
            if (xmlHttp.status == 200 || (xmlHttp.status >= 300 && xmlHttp.status<=399 )) {
                manageAnswerAboutEmail(xmlHttp.responseText);
            } else {
                alert(EMAIL_CONNECTION_ERROR + xmlHttp.status);
            }
        }
        return;
    }
    
    var sendPortlet = customSendPortlet;
    if(!sendPortlet){
    	sendPortlet = DEFAULT_SEND_PORTLET;
    }
    
    xmlHttp.open("POST", EMAIL_RESOURCE_ADDRESS + sendPortlet, true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send("r,main,specId=" + encodeURIComponent(specId)
    +"&"+"r,main,name=" + encodeURIComponent(name)
    +"&"+"r,main,surname=" + encodeURIComponent(surname)
    +"&"+"r,main,phone=" + encodeURIComponent(phone)
    +"&"+"r,main,email=" + encodeURIComponent(email)
    +"&"+"r,main,zipcode=" + encodeURIComponent(zipcode)
    +"&"+"r,main,city=" + encodeURIComponent(city)
    +"&"+"r,main,question=" + encodeURIComponent(question)
    +"&"+"r,main,mailconfigId=" + encodeURIComponent(configId));
    
    document.getElementById('_SPECID').value = specId;
    showAFLayer();
    
}

function manageAnswerAboutEmail(serverResp) {
    if (serverResp != null ) {
        serverResp = eval(serverResp);
        document.getElementById('_SENT').value = serverResp[0];        
    } else {
        alert(EMAIL_NULL_SERVER_RESP);
    }
//    pause(7000);
    hideAFLayer('AgentFormDiv');
    return document.getElementById('agentForm').submit();
}


    function hideAFLayer(parentID) {
        
        moveAFLayerFromBody(parentID);
        var _WAIT = document.getElementById("AFwait");
        var _SHADOW1 = document.getElementById("AFshadow");
        var _IFRAME = document.getElementById('AGENT_FORM_IFRAME');
        _WAIT.style.display = 'none';
        _SHADOW1.style.display = 'none';
        _SHADOW1.style.cursor = 'auto';
        _IFRAME.style.display = 'none';
    }
    
    function showAFLayer() {
        fields = new Array();
        fields['inforecipientFR']=false;
        fields['infosenderFR']=false;
        fields['infosignatureFR']=false;
        
      //  alert('Nazwa przegladarki: ' + navigator.userAgent + ' '+'Wersja przegladarki:' + navigator.appVersion);
        
        moveAFLayerToBody();
        
        var _FIELD1 = document.getElementById("DX0");
        var _BODY = document.getElementsByTagName("body")[0];
        var _WAIT = document.getElementById("AFwait");
        var _SHADOW1 = document.getElementById("AFshadow");
        var _IFRAME = document.getElementById('AGENT_FORM_IFRAME');
        
        _IFRAME.style.display = "block";
        _SHADOW1.style.display = "block";
        _WAIT.style.display = "block";
      
        if( _BODY != null ){
            var coords = getElementCoords( _BODY );
            var coords1 = getElementCoords( _FIELD1 );
            
            _IFRAME.style.top = coords.y + "px";
            _IFRAME.style.left = coords1.x + "px";
            _IFRAME.style.width = coords1.w  + "px";
            _IFRAME.style.height = (coords.h ) + "px"; 
            
            _SHADOW1.style.top = coords.y + "px";
            _SHADOW1.style.left = coords1.x + "px";
            _SHADOW1.style.width = coords1.w  + "px";
            _SHADOW1.style.height = (coords.h ) + "px"; 
            
            _WAIT.style.top = ((coords.y + coords.h / 2) - _WAIT.offsetHeight/2) + "px";
            _WAIT.style.left = ((coords.x + coords.w / 2) - _WAIT.offsetWidth/2) + "px";

        }  
        
        _IFRAME.style.visibility = "visible";
        _SHADOW1.style.visibility = "visible";
        _SHADOW1.style.cursor = 'wait';
        _WAIT.style.visibility = "visible";
        
        
    }  
    
    
     /**
     * przenosi popup wraz z cieniem przykrywajacym strone
     * do elementu body
     */
    function moveAFLayerToBody(){
        if(checkBrowser()) {
            var _BODY = document.getElementsByTagName("body")[0];
            var _WAIT = document.getElementById("AFwait");
            var _SHADOW = document.getElementById("AFshadow");
            var _IFRAME = document.getElementById('AGENT_FORM_IFRAME');
            _IFRAME.parentNode.removeChild(_IFRAME);
            _SHADOW.parentNode.removeChild(_SHADOW);
            _WAIT.parentNode.removeChild(_WAIT);
            _BODY.appendChild(_IFRAME);   
            _BODY.appendChild(_SHADOW);   
            _BODY.appendChild(_WAIT);  
 
        }
    }
    /**
     * przenosi popup wraz z cieniem przykrywajacym strone
     * z body do poprzedniej lokalizacji
     */
    function moveAFLayerFromBody(destination){    
        if(checkBrowser()) {
            var _BODY = document.getElementsByTagName("body")[0];
            var _WAIT = document.getElementById("AFwait");
            var _SHADOW = document.getElementById("AFshadow");
            var _IFRAME = document.getElementById('AGENT_FORM_IFRAME');
            var _DESTINATION = document.getElementById(destination);
            _IFRAME.parentNode.removeChild(_IFRAME);
            _SHADOW.parentNode.removeChild(_SHADOW);
            _WAIT.parentNode.removeChild(_WAIT);
            _DESTINATION.appendChild(_IFRAME);   
            _DESTINATION.appendChild(_SHADOW);
            _DESTINATION.appendChild(_WAIT);    
        }  
    } 
    
    function pause(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    }   
    