//get the country code
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="http://adwingate.com/emarketing/geoip/countryCode.js.php"></script>');
//the interval value
var ival = false ;

//A function to use to catch errors on wierd browsers
function catchAll(e){
    console.debug(e);
    message = " I'm sorry, we could not continue. If this problem continues please contact customer support. ( please provide support with the following error message:" + e +")";
    linkUrl = "registration.aspx";
    try{
        $('registrationForm').show().update((new Element('p')).update(message)).insert(new Element('a', {  href: linkUrl }).update("Click Here To Try the old form"))  ;
    }
    catch(e2){
        alert(message);
        window.location = linkUrl;
    }

}

//Loads the TLData from the cookie into hidden fields .
function parseTLCookie () {
    var TLCookieResult = /TLCookie=([^;]*)/.exec(document.cookie);
    if(TLCookieResult){
//ther is a problem with parsing the query sometimes// need to find a solution
        var TLCookie = TLCookieResult[1].parseQuery();
        for(cName in TLCookie ){
            if(TLCookie[cName] && $(cName)){
                $(cName).value= TLCookie[cName];
            }
        }
        if(ival != false ){
            //if we got the cookie then stop looking.
            clearInterval(ival);
        }
        console.log("got parseTLCookie");
        console.debug(TLCookie);
    }
    else{
        TLCookie = false;
    }

    
    return TLCookie ;
}


//Be sure that the script from JSforallpages.js is on each page.
//registrationUrl = "http://www.clickforex.com/HttpHandlers/api/RegisterUser.ashx";
registrationUrl = "HttpHandlers/api/RegisterUser.ashx";
//registrationUrl = "http://www.clickforex.com/HttpHandlers/LRU.ashx" ;
var result = null;


var comfirmationPixels = 
//English: 
'<IMG SRC="http://secure.fxcash.com/track_lead/38/">' +
//French: 
'<IMG SRC="http://secure.fxcash.com/track_lead/39/">' +
// German:
'<IMG SRC="http://secure.fxcash.com/track_lead/40/">' +
// Italian:
'<IMG SRC="http://secure.fxcash.com/track_lead/37/">' +
// Russian:
'<IMG SRC="http://secure.fxcash.com/track_lead/41/">' +
// Spanish:
'<IMG SRC="http://secure.fxcash.com/track_lead/42/">' +
// Default:
'<IMG SRC="http://secure.fxcash.com/track_lead/84/">' +
// Demo account (multilanguage): 
'<IMG SRC="http://secure.fxcash.com/track_lead/19/">' ;
if(!console){
    // this makes console not trigger error in browsers that don't support it ..
    try{
        var console = new Object;
        console.log = function() {};
        console.debug = function(){};
    }
    catch(e){
        // we were not able to start console, but don't die
    }
}

try{
    Event.observe(window, 'load',
    //document.observe("dom:loaded",
    function() {
        
        console.debug('loaded');
        
        // =============================
        // = putting lables in the default value =
        // =============================
        //This must be before setting any default values
        try{
            $$('input[type=text]').each(function(textField){
                //save the text value
               textField.prevVal = textField.value;
               textField.
                  observe('focus',function(){
                      if(this.prevVal && this.value==this.prevVal){
                          $(this).value = '';
                      }
                  }).
                  observe('blur',function(){
                      if(this.prevVal && $(this).value==''){
                          $(this).value=this.prevVal;
                      }
                  })
            });
        }
        catch(e){
            console.debug("default values failed to be set");
            console.debug(e);
        }
        
        // ========================
        // = GETTING COUNTRY CODE =
        // ========================
        $('CountryCode').observe('change',function(eve){
            if(countryCodes[this.value]){
                $('phone1').value = countryCodes[this.value];
            }
	    else{
		$('phone1').value = '' ;
	    }	
        })
        //try to set the default 
        if(typeof geoipCountryCode=='string' && geoipCountryCode.length==2){
            $('CountryCode').value = geoipCountryCode;
            if(countryCodes[geoipCountryCode]){
                $('phone1').value = countryCodes[geoipCountryCode];
            }
        }
        /*
            TOOL TIPS
        */
        try{
            $$('input[type="text"]').each(function(e){
                console.debug(e);
                tooltipId = e.id+'-tip' ;
                tooltip = $(tooltipId);
                if(!tooltip && e.title){
                    tooltip = new Element('a');
                    tooltip.id = tooltipId;
                    tooltip.innerHTML = "?"
                    e.insert({ after: tooltip })
                    tooltip.addClassName('tooltip')
                }
                if(tooltip){
                    if(!(tooltip.title)){
                        tooltip.title= e.title;
                    }
                    tooltip.observe('click',function(){alert(this.title)})
                }
            })
        }
        catch(e){
            console.debug('tool tips not loaded' + e);
        }
        /*
            TODO get values from cookie or set defaults
        */
    
        try{//create template and validation
            //create templates
            var welcomeTemplate = new Template($('welcomeMessage').innerHTML);

            //loading data from cookies // defaults can be set in the HTML form
            var TLResult = parseTLCookie();
            //Check if we got the adData, if not try to get it in iFrame
            if(TLResult ==false || !$('AdData').value  ){
                var urlArray = new Array();
                urlArray['en'] = 'http://secure.fxcash.com/sw/2698/CD530/';
                urlArray['it'] = 'http://secure.fxcash.com/sw/2703/CD530/';
                urlArray['fr'] = 'http://secure.fxcash.com/sw/2701/CD530/';
                urlArray['es'] = 'http://secure.fxcash.com/sw/2702/CD530/';
                // match the language from the url string
                var langMatches = document.location.pathname.match(/^\/([a-z]{2})($|\/)/i);
                if(!langMatches || !langMatches[1] || !urlArray[langMatches[1]])
                {
                    // if the language string turns out empty, set to english
                    var srcUrl = urlArray['en'];
                }
                else
                {
                    //set url to the language we detected
                    var srcUrl = urlArray[langMatches[1]];
                }
                var cookieFrame = new    Element('iframe',{
                       'src': srcUrl,
                       'width':0 ,
                       'height':0,
                       'frameborder':0
                       });

                $$('body')[0].appendChild(cookieFrame);
                ival = setInterval(parseTLCookie,250);
            }
            // ['AdServer','AdData','TLID'].each(function(cName){
            //         if(cookie=getCookie(cName)){
            //             $(cName).value=cookie;
            //         }
            //     });
    
            //hide and show , all of these elements should be set to hide in inline CSS 

            $('registrationForm').show();


    
            $('welcomeMessage').hide();
    
            //setup validation
            Validation.add('validate-name','Please enter a valid first name in English - must be 2 - 20 characters long (valid characters are: A-Z, a-z, -, .)',{
                pattern : new RegExp("^[a-z\.\-]{2,20}$","i")
            });

            Validation.add('validate-phone','Please enter in the following format where [] is optional: 0[00]-0[000]-0000[000000].If there is no area code, insert 0.',{
                pattern: new RegExp('^[0-9]{1,3}-[0-9]{1,4}-[0-9]{4,10}$',"i")
            }); 
            Validation.add('required', 'This is a required field.', function(v,elm) {
                    if(elm.prevVal){
                        if(elm.prevVal == v){
                            return false;
                        }
                    }
                   return !Validation.get('IsEmpty').test(v);
                 }
            ); 
            $('FirstName').addClassName('validate-name').addClassName('required');
            $('LastName').addClassName('validate-name').addClassName('required');
    
            $('Email').addClassName('validate-email').addClassName('required');
    
            //$('PhoneBody').addClassName('validate-phone').addClassName('required');
    
            $('CountryCode').addClassName('required');
    
            /*
                TODO also add validators for User Name and password
            */
            var valid = new Validation(
                $$('Form')[0], {onSubmit:false,immediate:true,useTitles:true,
                    onFormValidate : function(result){
                        var validationBox = $('validation-alert');
                       
                        if(result){
                            if(validationBox){
                                $(validationBox).hide();
                            }
                        }
                        else{
                            /*
                             ## This is a Hack ##
                             
                             We are showing the validation box, so we can fetch the validation messages
                             and showing them in the alert and then hiding the alert message.
                             
                             */
                            if(validationBox){
                                $(validationBox).show();
                            }
                            
                            //show the alert box on submit
                            var alertMsg = "";
                            $$('.validation-advice').each(function(e) {
                                if (e.visible()) {
                                    alertMsg = alertMsg + "\n\n" + e.innerHTML.stripTags(); 
                                }
                            })
                            //after showing the alert hide the messages
                            if(validationBox){
                                $(validationBox).hide();
                            }
                            alert(alertMsg);
                        }
                            
                        
                    }
                    
                }
            );    
    
            $$('input.phone-part').invoke('observe','blur', function(){
                $('PhoneBody').value = $F('phone1') + '-' + $F('phone2') + '-' + $F('phone3');
		//$('Phone').value = $F('phone1') + '-' + $F('phone2') + '-' + $F('phone3');
                //$('PhoneBody').simulate('blur');
            })
    
            $$('input.phone-part').invoke('addClassName','required');
    
            Validation.add('validate-countrycode','Country code must be between 1 and 3 numbers, do not add + .',{
                pattern: new RegExp('^[0-9]{1,3}$',"i")
            });
            Validation.add('validate-areacode','Area code must be between 1 and 4 numbers.',{
                   pattern: new RegExp('^[0-9]{1,4}$',"i")
            });
            Validation.add('validate-phone-part','Please enter a valid phone number between 4 and 10 numbers, no dashes.',{
                   pattern: new RegExp('^[0-9]{4,10}$',"i")
            });
    
            $('phone1').addClassName('validate-countrycode');
            $('phone2').addClassName('validate-areacode');
            $('phone3').addClassName('validate-phone-part');
        }
        catch(e){
            catchAll(e);
	    console.debug('setting up validation line:162');
        }
        
        //Add submit handler
        $$('Form')[0].observe("submit",
        function(event){
            
            try{ //pre send 
                /*
                generate username and password
                */
                $('Username').value =
                (
                    $F('FirstName').capitalize().truncate(5, '').gsub(/\W/, '') +
                    $F('LastName').capitalize().truncate(3, '').gsub(/\W/, '') + Math.floor((((new Date).getTime()) % (60 * 60 * 1000)) / (1000))
                );
        
                $('Password').value =
                (
                    $F('LastName').capitalize().truncate(5, '').gsub(/\W/, '') + 
                    Math.floor((((new Date).getTime()) % (60 * 60 * 1000)) / (1000)) + 
                    $F('FirstName').capitalize().truncate(3, '').gsub(/\W/, '')
                );

                //extract language
                var lang =null;
                if($('Lang')){
                    lang = $F('lang');
                }
                if(!lang){
                    lang_result = /\/(\w{2})\//i.exec(document.location.pathname);
                    if(lang_result && lang_result.length==2){
                        lang = lang_result[1];
                    }
                    else{
                        lang = 'en';
                    }
                    lang = lang.toLowerCase();
                }
        
        
                /\/(\w{2})\//i.exec(document.location.pathname);
                //VALIDATE form
                // var result = true;
                var result = valid.validate();
            }
            catch(e){
                catchAll(e);
            }
            if(result){
                
                try{//after validate, before sending
        
                    console.debug("Submiting form ");
                    if($F('debug')==1){
                        $('TLID').value=1;
                        $('BusinessUnit').value=0;
                    }
                    params = $$('Form')[0].serialize(true);
        
                    //requesting JSON format
                    params.responseFormat = 1
            
                    //This is for compatability with other versions of the API
                    params['TrackingLinkId']= params.TLID; 
                    params['language'] = lang;
           
            
                    console.debug(params);
                }catch(e){
                    catchAll(e);
                }
                new Ajax.Request(registrationUrl,{
                    // method:'post',
                    contentType:'application/x-www-form-urlencoded',
                    parameters: params,
                    onCreate: function(){$$('FORM')[0].disable()},
                    onComplete: function(){$$('FORM')[0].enable()},
                    onSuccess: function(transport,json) {
                        try{
                           console.debug(registrationUrl);
                           console.debug(transport);
                           var isok=false ;
                           var ErrorMessage;
                           var ErrorCode;
                           if(transport.responseText.isJSON()){
                               json=transport.responseText.evalJSON();
                               console.debug(json);
                               isok = (json.isok=="True");
                           }
                           else{// XML 
                               //parse some errors
                               console.debug(transport.responseText);
                               ErrorCode = /<ErrorCode>(\w*)<\/ErrorCode>/i.exec(transport.responseText);
                               console.debug(ErrorCode)
                               if(ErrorCode){
                                   //extract the code
                                   ErrorCode=ErrorCode[1];
                               }
                               ErrorMessage = /<ErrorMessage>([^<]*)<\/ErrorMessage>/i.exec(transport.responseText);
                               console.debug(ErrorMessage);
                               if(ErrorMessage){
                                   //extract the code
                                   ErrorMessage=ErrorMessage[1];
                               }
                               isok = (ErrorCode == "RC_OK")
                       
                           }
                   
                           if($F('debug')==1){
                               isok =1
                           }
                   
                           if( !isok){
                               //we shouldn't get here , we should do some JS validation first.
                               alert('There was an error');
                               if(transport.responseText.isJSON()){
                                   fields = json.fields;
                                   console.debug(fields);
                                   for(fieldName in fields){
                                       console.debug(fieldName);
                                       field = json.fields[fieldName];
                                       console.debug(field);
                                       if(field.isok == "False"){
                                           alert( 'Field: ' + fieldName + ' is  problematic');
                                       }
                                   }
                               }
                               else{
                                   alert(ErrorMessage);
                               }
                           }
                           else{
                               /*
                                TODO Test load tracking pixel 
                                Checked that they loaded on ie6 and safari , but how do we check that they are actually registering the lead ?
                               */
                               //Display Welcome message.
                               // $('conf_code').value= json.conf_code;
                               $('registrationForm').hide();              
                               $('welcomeMessage').update(welcomeTemplate.evaluate($$('Form')[0].enable().serialize(true)) + comfirmationPixels ).show()
                               //getting rid of this garbage
                               params['__VIEWSTATE']='';
                       
                               //split up add data
                               var temp = params.AdData.split('_');
                               params.aid = temp[0];
                               params.bid = temp[1];
                               params.cid = temp[2];
                               params.did = temp[3];
                               params.cookieid = temp[4];
                                                                                            
                               img = new    Element('img',{
                                   'src':'http://adwingate.com/emarketing/clickForexAddLead.php?list_id=186&'+Object.toQueryString(params)
                                   }).observe('load',console.debug(this));
                           }
                       }
                        catch(e){
                            catchAll(e);
                        }
                     }
                
                 
                 
            })
            }
            Event.stop(event);
            return false;
        })
    }
    )}
catch(e){
    catchAll(e);
}
