/* 
crann.js: library of javascript for animation / branding effects
    david.kelly@fanore.com (http://www.fanore.com/website_design.htm)
    
  setup_page: triggered when the page has completed loading
  fix_height: ensure that page reaches to bottom of the viewport  
  load_map: populate and initialise Google map
  submit_form: utility that will perform client side validation of the passed form id and allow validator to post it   
  open_link: used to open a new window full screen  
  validate_search: tests the search dialogue before posting      
*/

var gallery=false;

jQuery(document).ready(function($){setup_page();});
//  setup_page: triggered when the page has completed loading
function setup_page(){
    // preload images
    //$('#content').fadeOut(100);
 //alert("here")
    //alert($().jquery);
    if ($('#map').length){
        eval('load_map();');
    }


    if ($('#email').length){
        //alert("here")
        $("#email").bind("click", function(event){
           if ($('#email').val()=='email address'){
            $('#email').val('');
           } 
        });
    }    
    popupBinding();
    trialBinding();
    outbound_links();
    fix_height();
    digitTabbing();

}

//trialBinding: bind to the free trial button, triggering a popup dialogue that posts and directs to the loyalty.ie signup page
function trialBinding(){
    if($('#null_form').length){
        $('#null_form').submit(function(e){
            //popup dialogue prompto
            e.preventDefault();
            var target='#trialPopup' 
            var url=$('#nullURL').val().replace('z-','z-_'); 
            var errorURL=$('#nullURL').val();
            //window.location.href=errorURL
              $(target).load(url, function(response, status, xhr){      
                         if (status=='error')
                         { // handle error messaging here
                            // if in development environment we redirect to the url so we can get an idea of what the problem is
                            window.location.href=errorURL
                            
                         }
                         else
                         {
                         // alert("here");
                         //overlay dialogue
                                 $(target).overlay({
                                            effect: 'apple',
                                            speed: 'fast',
                                        	expose: {
                                        		color: '#000',
                                        		loadSpeed: 200,
                                        		opacity: 0.5
                                        	},
                                            //close: '.wrapButtons .cancelButton',
                                            onLoad: function(){ 
                                               $('#but_cancel').bind('click',function(e){
                                                    e.preventDefault();
                                                    $(target).overlay().close();
                                                  }); 
                                               $('#formFreeTrial').submit(function(e){
                                                    //e.preventDefault();
                                                    //$(target).overlay().close();
                                                    // validate form values
                                                    if (validatePreliminary()==true){
                                                        var track=$('#u_base').val() + '-z-conversion.htm'
                                                        jQuery.get(track); 
                                                        var q=$(this).serialize();
                                                        var u=$('#u_base').val() + 'asp/fanore.asp?' + q + '&track=true'

                                                        jQuery.get(u); 
                                                        
                                                        //alert(u);
                                                        return true;
                                                    }
                                                    e.preventDefault();
                                                    return false;
                                                    //capture form values and post to local handler before proceeding
                                                    
                                                    
                                                  }); 
                                            }, 
                                        	closeOnClick: false,
                                            api: true
                                        	
                                        }).load();
                         }
                 });//end load
         
                
        });
    }
    
    $('a[href*="trial.htm"]').each(function(){
        $(this).bind('click',function(e){
            e.preventDefault();
            var target='#trialPopup' 
            var url=$(this).attr('href').replace('z-trial.htm','z-_preliminary.htm'); 
            var errorURL=url
            //window.location.href=errorURL
              $(target).load(url, function(response, status, xhr){      
                         if (status=='error')
                         { // handle error messaging here
                            // if in development environment we redirect to the url so we can get an idea of what the problem is
                            window.location.href=errorURL
                            
                         }
                         else
                         {
                         // alert("here");
                         //overlay dialogue
                                 $(target).overlay({
                                            effect: 'apple',
                                            speed: 'fast',
                                        	expose: {
                                        		color: '#000',
                                        		loadSpeed: 200,
                                        		opacity: 0.5
                                        	},
                                            //close: '.wrapButtons .cancelButton',
                                            onLoad: function(){ 
                                               $('#but_cancel').bind('click',function(e){
                                                    e.preventDefault();
                                                    $(target).overlay().close();
                                                  }); 
                                               $('#formFreeTrial').submit(function(e){
                                                    //e.preventDefault();
                                                    //$(target).overlay().close();
                                                    // validate form values
                                                    if (validatePreliminary()==true){
                                                        
                                                        var q=$(this).serialize();
                                                        var u=$('#u_base').val() + 'asp/fanore.asp?' + q + '&track=true'

                                                        jQuery.get(u); 
                                                        
                                                        //alert(u);
                                                        return true;
                                                    }
                                                    e.preventDefault();
                                                    return false;
                                                    //capture form values and post to local handler before proceeding
                                                    
                                                    
                                                  }); 
                                            }, 
                                        	closeOnClick: false,
                                            api: true
                                        	
                                        }).load();
                         }
                 });//end load
            
        });
    });
    
}

//validatePreliminary: valiate preliminary form, record results and return true if all ok
function validatePreliminary(){
    //txt_name
    if ($('#txt_name').val().length==0){
        alert("Please enter a contact name!");
        $('#txt_name').focus();
        return false;
    }
    
    //email address
    if ($('#txt_email').val().length==0){
        alert("Please enter a contact email address!");
        $('#txt_email').focus();
        return false;
    }
    var e=$('#txt_email').val();
    if (!check_email(e,true)){
        alert("Please check that you have entered a valid  email address!");
        $('#txt_email').focus();
        return false;
    
    }

    //telephone
    var telephone=fix_telephone($('#txt_telephone').val());
    $('#txt_telephone').val(telephone);
    
    if (telephone.length==0){
        alert("Please enter a contact telephone number!");
        $('#txt_telephone').focus();
        return false;
    }
    var img=new Image();
    img.src="http://aaf.tradatracker.net/track/conv.gif?advertiser=e00da03b685a0dd18fb6a08af0923de0&action=Signup"
    //var track=$('#u_base').val() + '-z-conversion.htm'
    //jQuery.get(track);     
    return true;
}

//popupBinding: bind to links classed as popup triggers
function popupBinding(){
if ($(".pop").length){
    $('a.pop').bind("click",function(e){
        e.preventDefault();
        var target='#ajaxPopup' 
        var url=$(this).attr('href').replace('z-','z-_'); 
        var errorURL=$(this).attr('href');
        
      $(target).load(url, function(response, status, xhr){      
                 if (status=='error')
                 { // handle error messaging here
                    // if in development environment we redirect to the url so we can get an idea of what the problem is
                    window.location.href=errorURL
                    
                 }
                 else
                 {
                 // alert("here");
                 //overlay dialogue
                         $(target).overlay({
                                    effect: 'apple',
                                    speed: 'fast',
                                	expose: {
                                		color: '#000',
                                		loadSpeed: 200,
                                		opacity: 0.5
                                	},
                                    //close: '.wrapButtons .cancelButton',
                                    onLoad: function(){ 
                                       $('#closePanel').bind('click',function(e){
                                            e.preventDefault();
                                            $(target).overlay().close();
                                          }); 
                                    }, 
                                	closeOnClick: false,
                                    api: true
                                	
                                }).load();
                 }
         });//end load
         
         });//end bind to click
    }
       
}
function dateBinding(){
    if ($('#dataBirthday').length){
        $('#dataBirthday').datepicker({ dateFormat: 'dd MM yy' } );
        $('#dataBirthday').bind('keydown',function(e){e.preventDefault();});
        }

}


//outbound_links: ensure that outbound links open in a new window
function outbound_links(){
    $("a", "#keep_together").bind("click", function(event){  
    var b=$('#u_base').val();
    var href=$(this).attr("href").toString();
        if ((href.indexOf(b)==-1)&&(href.indexOf('javascript')==-1)&&(href.indexOf('mailto')==-1)&&(href.indexOf('../')==-1)){
            var n_ref='javascript: open_link(\'' + href + '\');';
            $(this).attr("href",n_ref);
         }
    });     
    
}


function check_subscribe(){
//email address
    if ($('#email').val().length==0){
         show_error_message("please enter your email address!",'error_message_panel');
        $('#email').focus();
        return false;
    }
    var e=$('#email').val()
	if (!check_email(e,true)){
		alert("The email address you have entered seems to be invalid - this system only supports the format 'yourname@address.com' !");
        $('#email').focus();
		return false;
	}
    $('#your_details').val('');
    return true;
}
//      fix_height: ensure that page reaches to bottom of the viewport
function fix_height(){
 
    var h=$(window).height()-356
    var d=$(document).height()-356
    //alert(d)
    //alert(h)
    if (h<d){h=d}
    if (($('#keep_together').height()) < h){
       $('#keep_together').height(h);
    }
    else{
       $('#keep_together').height('auto');    
    }
    if (($('div.www_content').height()) < h){
       //$('div.www_content').height(h);
    }
    else{
       // alert("here")
       $('div.www_content').height('auto');    
    }
    
    
    
}

//  load_map: populate and initialise Google map
function load_map() {
//  alert("map")
    var lat=53.08776129009672;
    var lon=-9.314088821411132;
    var c_lat=53.10062087921428;
    var c_lon=-9.29443359375;
    if (GBrowserIsCompatible()) {
        var map = new GMap(document.getElementById("map"));
        map.addControl(new GLargeMapControl())
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(c_lat, c_lon), 7);
        //var blueIcon = new GIcon(G_DEFAULT_ICON);
        //blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";        		
        var html='<strong>Glenvane House</strong><br/>Fanore<br/>Co. Clare<br/>Ireland<br/>+353'
        var point = new GPoint(parseFloat(lon), parseFloat(lat));
        var marker = new GMarker(point);
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
        icon.iconSize = new GSize(20,20);
        icon.iconAnchor = new GPoint(10,20);
        icon.infoWindowAnchor = new GPoint(10, 20);
        var marker = new GMarker(point,icon);   
        //GEvent.addListener(marker, "mouseover", function() {
        //marker.openInfoWindowHtml(html);
        //});
        map.addOverlay(marker);
        return marker
    }
 }

//  submit_form: utility that will perform client side validation of the passed form id and allow validator to post it 
function submit_form(param_form){
    var el=get_el("cs_validation");
    //alert("here");
    if (el){
        var f=$(param_form)
        var cs_validation=f['cs_validation'];
         return eval($(cs_validation).getValue());
    }
    else{
        $(param_form).submit();
    }
}

//  open_link: used to open a new window full screen
function open_link(url){
 var settings='Height=' + screen.height + ',Width=' + screen.width + ',Top=0,left=0,scrollbars=yes,resizable=1, location=1,status=1'
 var w=window.open(url,'glenvane',settings);    
}


// validate_registration_form: test the values entered on registration form
function validate_registration_form(){
//organisation
    if ($('#txt_organisation').val().length==0){
         show_error_message("please enter the company or organisation name!",'error_message_panel');
        $('#txt_organisation').focus();
        return false;
    }
//title
   // if ($('#txt_title').val().length==0){
   //      show_error_message("please enter the contact title (e.g. Mr. / Ms.)!",'error_message_panel');
   //     $('#txt_title').focus();
   //     return false;
   // }
//firstname
    if ($('#txt_firstname').val().length==0){
         show_error_message("please enter the billing contact's first name!",'error_message_panel');
        $('#txt_firstname').focus();
        return false;
    }
//surname
    if ($('#txt_surname').val().length==0){
         show_error_message("please enter the billing contact's surname!",'error_message_panel');
        $('#txt_surname').focus();
        return false;
    }
//email
    if ($('#txt_email').val().length==0){
         show_error_message("please enter the billing email address!",'error_message_panel');
        $('#txt_email').focus();
        return false;
    }
//validate email address
    var e=$('#txt_email').val();
	if (!check_email(e,true)){
		alert("The email address you have entered seems to be invalid - this system only supports the format 'yourname@address.com' !");
        $('#txt_email').focus();
		return false;
	}
    
//address 1
    if ($('#txt_address1').val().length==0){
         show_error_message("please enter at least two lines for the address!",'error_message_panel');
        $('#txt_address1').focus();
        return false;
    }
//address 2
    if ($('#txt_address1').val().length==0){
         show_error_message("please enter at least two lines for the address!",'error_message_panel');
        $('#txt_address1').focus();
        return false;
    }
//address 3
//    if ($('#txt_address3').val().length==0){
//         show_error_message("please enter at least two lines for the address!",'error_message_panel');
//        $('#txt_address3').focus();
//        return false;
//    }
//address 4 (county)
    if ($('#txt_address4').val().length==0){
         show_error_message("please select the county!",'error_message_panel');
        $('#txt_address4').focus();
        return false;
    }
//telephone
    if ($('#txt_telephone').val().length==0){
         show_error_message("please enter a contact telephone number!",'error_message_panel');
        $('#txt_telephone').focus();
        return false;
    }
//mobile
//    if ($('#txt_mobile').val().length==0){
//         show_error_message("please enter a mobile number!",'error_message_panel');
//        $('#txt_mobile').focus();
//        return false;
//    }
//fax
//    if ($('#txt_fax').val().length==0){
//         show_error_message("please enter a fax number!",'error_message_panel');
//        $('#txt_fax').focus();
//        return false;
//    }
//vat number
//    if ($('#txt_vat').val().length==0){
//         show_error_message("please enter a vat number!",'error_message_panel');
//        $('#txt_vat').focus();
//        return false;
//    }
return true;
}


function show_error_message(param_message,param_wrapper, param_div){
alert(param_message);
return void[0];
    if (param_div==false){
        alert(param_message);
    }
    else{
            $('#display_error_message').innerHTML=param_message;
            //$(param_wrapper).absolutize();
            //$(param_wrapper).setStyle({top: 200, left:400, zIndex:100});
            $('#display_error_message').show('slow');
            setTimeout(function(){hide_error_message(param_wrapper)},2000);
/*
            new Effect.Appear(param_wrapper,{
                duration: 0.5, 
                afterFinish: function(){
                setTimeout(function(){hide_error_message(param_wrapper)},2000);
            }});
*/            
    }
}
// hide the error message panel
function hide_error_message(param_wrapper){
    
        $('#' + param_wrapper).hide('slow');

}



function validate_form(){
//    alert('here');
    //txt_company
    if ($('#txt_company').val().length==0){
        alert("Please enter your company name!");
        $('#txt_company').focus();
        return false;
    }
    //txt_name
    if ($('#txt_name').val().length==0){
        alert("Please enter a contact name!");
        $('#txt_name').focus();
        return false;
    }
    
    //telephone
    var telephone=fix_telephone($('#txt_telephone').val());
    $('#txt_telephone').val(telephone);
    
    if (telephone.length==0){
        alert("Please enter a contact telephone number!");
        $('#txt_telephone').focus();
        return false;
    }

    //email address
    if ($('#txt_email').val().length==0){
        alert("Please enter a contact email address!");
        $('#txt_email').focus();
        return false;
    }
    var e=$('#txt_email').val();
    if (!check_email(e,true)){
        alert("Please check that you have entered a valid  email address!");
        $('#txt_email').focus();
        return false;
    
    }
    //message
    if ($('#txt_comment').val().length==0){
        alert("Please tell us how we can assist!");
        $('#txt_comment').focus();
        return false;
    }
    
    $('#your_details').val('');
    //
    
    return true;
 }
 


function validate_entry(){
    //txt_name
    if ($('#txt_name').val().length==0){
        alert("Please enter a contact name!");
        $('#txt_name').focus();
        return false;
    }
    
    //telephone
    var telephone=fix_telephone($('#txt_telephone').val());
    $('#txt_telephone').val(telephone);
    
    if (telephone.length==0){
        alert("Please enter a contact telephone number!");
        $('#txt_telephone').focus();
        return false;
    }

    //email address
    if ($('#txt_email').val().length==0){
        alert("Please enter a contact email address!");
        $('#txt_email').focus();
        return false;
    }
    var e=$('#txt_email').val();
    if (!check_email(e,true)){
        alert("Please check that you have entered a valid  email address!");
        $('#txt_email').focus();
        return false;
    
    }
    //reference
    if ($('#reference').val().length==0){
        alert("Please enter your promotional code!");
        $('#reference').focus();
        return false;
    }
    
    $('#your_details').val('');
    //
    
    return true;
 }
 



function check_email(svalue, bmail){
    var str=svalue;
    var sinvalid="!,£,\$,%,',\&";
    
    if (bmail==true){
    	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(')|(%)|(")/; // not valid
    	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
    }
    else{
    	var reg1 = /(\.\.)|(^\.)|(')|(%)|(")/; // not valid
    	var reg2 = /([a-zA-Z0-9])|([a-zA-Z])|([0-9])/; // valid
    
    }
    if (!reg1.test(str) && reg2.test(str)) { // if syntax is valid
    	return true;
    	}
    return false;
}



//fix_telephone: removes non-numeric characters from user entry
function fix_telephone(param_value){
    var ret_value='';
    var wip_value=param_value;
    var a_values='1234567890'
    //alert(wip_value.length);
    for (var i=0;i<=wip_value.length;i++){
    //alert(wip_value.charAt(i))
        for (var x=0;x<=a_values.length;x++){
            if (wip_value.charAt(i)==a_values.charAt(x)){
                ret_value+=wip_value.charAt(i)
            }
        }
    } 
    //alert(ret_value);
    return ret_value;   
}

//make_gallery: construct javascript object for animation of gallery
function make_gallery(param_url,param_images, param_target){
    this.url=param_url
    this.contents=new Array;
    this.current=0;
    this.target=param_target
    this.next=next_gallery_image
    this.start=start_gallery_animation
    this.update=show_current_image
    var b=param_images.split(',');
    for (var i=0;i < b.length;i++){
        var img=new Image 
        img.src=this.url + b[i]; 
        this.contents[this.contents.length]=img.src 
        if (i==1){
            this.start();
        }
    }
    return this;
}

function next_gallery_image(){

    var i=this.contents.length;
    this.current++
    if (this.current==i){
        this.current=0;
    }
    return this.contents[this.current]
}

function start_gallery_animation(){
					$('ul#image_gallery').innerfade({
						speed: 2000,
						timeout: 10000,
						type: 'sequence',
						containerheight: '558px'
					});
					$('li','#image_gallery').removeClass('no_show');
    
  //  setTimeout(function(){
  //      gallery.update();
  //  },3000)
}

function show_current_image(){
    var src=this.next();
    //alert(this.target);
    $('#' + this.target).attr('src',src);
    setTimeout(function(){
        gallery.update();
    },3000)
}





function validateSignUp(){
    //validate form elements based on their class
    var b=$('#requiredElements').val();
    var arrayElements=b.split(',');
    var bDay=false;
    var hasPhone=false;
    for (var i=0; i<arrayElements.length;i++){
        var nameSearch=arrayElements[i] + 'other';
        //alert(nameSearch);
        if ($('#'+nameSearch).length){
            if (($('#'+nameSearch).val().length!=0)&&($('#'+nameSearch).val()!='please specify')){
            //alert($('#'+nameSearch).val());
                $('#' + arrayElements[i]).val($('#'+nameSearch).val());
            }
        }
    
    var specialTreatment=arrayElements[i].replace('data','').toLowerCase(); // some fields require additional testing / special treatment
    if ((specialTreatment=='phonenumber')||(specialTreatment=='faxnumber')){//only execute when we get to either phone or mobile
               if (!hasPhone){
                if (($('#dataPhoneNumber').length) && ($('#dataFaxNumber').length)){
                            var telephone=fix_telephone($('#dataPhoneNumber').val());
                            $('#dataPhoneNumber').val(telephone);
                            
                            var landline=fix_telephone($('#dataFaxNumber').val());
                            $('#dataFaxNumber').val(landline);
                            
                            //one of these must be great than zero
            
                            //check again
                            if (($('#dataPhoneNumber').val().length==0)&&($('#dataFaxNumber').val().length==0)){
                                alert("You must enter either a landline or mobile number before proceeding!");
                                $('#dataPhoneNumber').focus();
                                return false;
                            }  
                            else{
                                hasPhone=true;
                            }
                           
                            
                            
                            if (hasPhone){//only check if the landline has been filled in 
                                //check again
                                if ($('#dataPhoneNumber').val().length!=0){
                                    //ensure that valid prefix has been selected         
                                    if ($('#phonePrefix').val().length==0){
                                        alert("Please select your mobile prefix from the list provided!");
                                        $('#phonePrefix').focus();
                                        return false;
                                    }
                                 }
                            }
                }//end test if landline & mobile elements on page
               }//end test if we've already evaluated one of these
        }
        // check if required element is one of our "special" items
        switch (specialTreatment){
            case 'emailaddress': // must be a valid email address format
                var e=$('#' + arrayElements[i]).val()
            	if (!check_email(e,true)){
            		alert("The email address you have entered seems to be invalid - this system only supports the format 'yourname@address.com' !");
                    $('#' + arrayElements[i]).focus();
            		return false;
            	}
                break;
            case 'phonenumber': //remove invalid characters from telephone number
                if (!hasPhone){//only need to check when exists in isolation
                
                        var telephone=fix_telephone($('#' + arrayElements[i]).val());
                        $('#' + arrayElements[i]).val(telephone);
                            //check again
                            if ($('#' + arrayElements[i]).val().length==0){
                                alert("You must enter a value for the " + $('#' + arrayElements[i].replace('data','caption')).text() + " before proceeding!");
                                $('#' + arrayElements[i]).focus();
                                return false;
                            }  
                            //ensure that valid prefix has been selected         
                            if ($('#phonePrefix').val().length==0){
                                alert("Please select your mobile prefix from the list provided!");
                                $('#phonePrefix').focus();
                                return false;
                            }
                    
                }                
                
                break;
            case 'faxnumber': //if fax number & phonenumber then faxnumber is landline
                if (!hasPhone){//only need to check when exists in isolation
                    var landline=fix_telephone($('#' + arrayElements[i]).val());
                    $('#' + arrayElements[i]).val(landline);
                    //check again
                    if ($('#' + arrayElements[i]).val().length==0){
                        alert("You must enter a value for the " + $('#' + arrayElements[i].replace('data','caption')).text() + " before proceeding!");
                        $('#' + arrayElements[i]).focus();
                        return false;
                    }  
                }
                break;
            case 'birthday'://ensure user has selected a date via datepicker
                if ($('#dob_day').val().length==0){
                    alert("Please select your date of birth!");
                    $('#dob_day').focus();
                    return false;
                }
                
                if ($('#dob_month').val().length==0){
                    alert("Please select your date of birth!");
                    $('#dob_month').focus();
                    return false;
                }
                
                if ($('#dob_year').val().length==0){
                    alert("Please select your date of birth!");
                    $('#dob_year').focus();
                    return false;
                }
                
                var today=new Date();
                var bday=new Date($('#dob_year').val() , parseInt($('#dob_month').val())-1 , $('#dob_day').val())
                var oneYear=1000*60*60*24*365
                var age=Math.floor( (today.getTime() - bday.getTime())/oneYear)
                if (age < 18){
                    alert("We're sorry but you must be over 18 to participate!");
                    $('#dob_year').focus();
                    return false;
                }
                $('#dataBirthday').val($('#dob_year').val() + '-' + $('#dob_month').val() + '-'  + $('#dob_day').val());
                bDay=true;
                break;
           default: //all others 
                if ($('#' + arrayElements[i]).val().length==0){
                    alert("You must enter a value for  " + $('#' + arrayElements[i].replace('data','caption')).text() + " before proceeding!");
                    $('#' + arrayElements[i]).focus();
                    return false;
                }
        }
        
        
        
    
    }
    
    //validate birthday (if optional)
    if ($('#dob_year').length){
        if (!bDay){
                var today=new Date();
                var bday=new Date($('#dob_year').val() , parseInt($('#dob_month').val())-1 , $('#dob_day').val())
                var oneYear=1000*60*60*24*365
                var age=Math.floor( (today.getTime() - bday.getTime())/oneYear)
                if (age < 18){
                    alert("We're sorry but you must be over 18 to participate!");
                    $('#dob_year').focus();
                    return false;
                }
                $('#dataBirthday').val($('#dob_year').val() + '-' + $('#dob_month').val() + '-'  + $('#dob_day').val());
        
        }
    }
    
    //capture value of grouped checkboxes (if any)
    //alert($('#groups').val());
    if ($('#groups').val().length!=0){
        var groupData=$('#groups').val();
        var groups=groupData.split(',');
        for (var x=0;x<groups.length;x++){
            var groupResult='';
            //loop through checkboxes
            var chk=$('input:checkbox');
            for (var c=0;c<chk.length;c++){
                if ($(chk[c]).attr('name')=='group' + groups[x]){
                    if ($(chk[c]).attr('checked')){
                        if (groupResult.length!=0){
                        groupResult+=","
                        }
                       groupResult+=$(chk[c]).attr('value')
                    }
                } 
            
            }
            //alert(groupResult);
            $('#dataGroup' + groups[x]).val(groupResult);
        }
    
    }
    //return false;
    var vCard=parseInt($('#validateCard').val());
    var minLength=parseInt($('#cardMin').val());
    var f=14;
    if (minLength!=0){
        f=minLength + 1;
    }
    
    var lCard=""
    if (vCard==1){
        //need to check the 13 digits
        var c=$('#cardPrefix').val();
        //alert(c);
        var p=0
        if (c.length!=0){
            p=parseInt($('#cardPrefix').val());
        }
        for (var x=1;x<f;x++){
           
                lCard+=$('#digit' + x).val();
            
            if ($('#digit' + x).val().length==0){
                alert("please enter your LOYALTY card number!");
                $('#digit' + x).focus();
                return false;
            }
            
            if (isNaN($('#digit' + x).val())){
                alert("please enter only digits shown on your LOYALTY card!");
                $('#digit' + x).val('');
                $('#digit' + x).focus();
                return false;
            
            }
            
            if ((x==1)&&(p!=0)){
                if (parseInt($('#digit' + x).val())!=p){
                alert("please check your entry as your LOYALTY card number does not seem to be valid!");
                $('#digit' + x).focus();
                return false;
               
                }
            }
        }
        
        
        }
      $('#cardNumber').val(lCard);
    return validateTermsAndConditions();

}


function validateTermsAndConditions(){
        var d=new Date();
        var target='#acceptancePopup' 
        var url=$('#acceptURL').val();
        var errorURL=url;
    $(target).load(url, function(response, status, xhr){      
                 if (status=='error')
                 { // handle error messaging here
                    // if in development environment we redirect to the url so we can get an idea of what the problem is
                    //alert("failed");
                    window.location.href=errorURL
                    
                 }
                 else
                 {
                    //alert("here");
                    //clone form
                    $('#acceptTitle').val($('#dataTitle').val());
                    $('#acceptFirstName').val($('#dataFirstName').val());
                    $('#acceptLastName').val($('#dataLastName').val());
                    $('#acceptAddress').val($('#dataAddress').val());
                    $('#acceptAddress2').val($('#dataAddress2').val());
                    $('#acceptCity').val($('#dataCity').val());
                    $('#acceptState').val($('#dataState').val());
                    $('#acceptZip').val($('#dataZip').val());
                    $('#acceptCountry').val($('#dataCountry').val());
                    $('#acceptCompany').val($('#dataCompany').val());
                    $('#acceptEmailAddress').val($('#dataEmailAddress').val());
                    if ($('#phonePrefix').length){
                    $('#acceptPhoneNumber').val($('#phonePrefix').val() + $('#dataPhoneNumber').val());
                    }
                    else{
                    $('#acceptPhoneNumber').val( $('#dataPhoneNumber').val());
                    }
                    $('#acceptFaxNumber').val($('#dataFaxNumber').val());
                    $('#acceptTaxNumber').val($('#dataTaxNumber').val());
                    $('#acceptBirthday').val($('#dataBirthday').val());
                    $('#acceptValidateCard').val($('#validateCard').val());
                    $('#acceptCardNumber').val($('#cardNumber').val());
                    
                    if (($('#dataCustomText1other').length) && ($('#dataCustomText1other').val()!='please specify')){
                        $('#acceptCustomText1').val($('#dataCustomText1other').val());
                    }
                    else
                    {
                        $('#acceptCustomText1').val($('#dataCustomText1').val());
                    }

                    if (($('#dataCustomText2other').length) && ($('#dataCustomText2other').val()!='please specify')){
                        $('#acceptCustomText2').val($('#dataCustomText2other').val());
                    }
                    else
                    {
                        $('#acceptCustomText2').val($('#dataCustomText2').val());
                    }
                    if (($('#dataCustomText3other').length) && ($('#dataCustomText3other').val()!='please specify')){
                        $('#acceptCustomText3').val($('#dataCustomText3other').val());
                    }
                    else
                    {
                        $('#acceptCustomText3').val($('#dataCustomText3').val());
                    }
                    if (($('#dataCustomText4other').length) && ($('#dataCustomText4other').val()!='please specify')){
                        $('#acceptCustomText4').val($('#dataCustomText4other').val());
                    }
                    else
                    {
                        $('#acceptCustomText4').val($('#dataCustomText4').val());
                    }
                    if (($('#dataCustomText5other').length) && ($('#dataCustomText5other').val()!='please specify')){
                        $('#acceptCustomText5').val($('#dataCustomText5other').val());
                    }
                    else
                    {
                        $('#acceptCustomText5').val($('#dataCustomText5').val());
                    }


/**
                    $('#acceptCustomText2').val($('#dataCustomText2').val());
                    $('#acceptCustomText3').val($('#dataCustomText3').val());
                    $('#acceptCustomText4').val($('#dataCustomText4').val());
                    $('#acceptCustomText5').val($('#dataCustomText5').val());
                    */
                    $('#acceptCustomDate1').val($('#dataCustomDate1').val());
                    $('#acceptCustomDate2').val($('#dataCustomDate2').val());
                    $('#acceptCustomDate3').val($('#dataCustomDate3').val());
                    $('#acceptCustomDate4').val($('#dataCustomDate4').val());
                    $('#acceptCustomDate5').val($('#dataCustomDate5').val());
                    $('#acceptCustomNumber1').val($('#dataCustomNumber1').val());
                    $('#acceptCustomNumber2').val($('#dataCustomNumber2').val());
                    $('#acceptCustomNumber3').val($('#dataCustomNumber3').val());
                    $('#acceptCustomNumber4').val($('#dataCustomNumber4').val());
                    $('#acceptCustomNumber5').val($('#dataCustomNumber5').val());
                    $('#acceptCustombool1').val($('#dataCustombool1').val());
                    $('#acceptCustombool2').val($('#dataCustombool2').val());
                    $('#acceptCustombool3').val($('#dataCustombool3').val());
                    $('#acceptCustombool4').val($('#dataCustombool4').val());
                    $('#acceptCustombool5').val($('#dataCustombool5').val());
                    $('#acceptGender').val($('#dataGender').val());
                    if ($('#dataAllowText').attr('checked')){
                        $('#acceptAllowText').val('1');
                    }
                    else{
                        $('#acceptAllowText').val('0');
                    }
                    if ($('#dataAllowEmail').attr('checked')){
                        $('#acceptAllowEmail').val('1');
                    }
                    else{
                        $('#acceptAllowEmail').val('0');
                    }
                    //deal with groups
                    
                    
                    
                    if ($('#groups').val().length!=0){
                        var groupData=$('#groups').val();
                        var groups=groupData.split(',');
                        for (var x=0;x<groups.length;x++){
                           // alert($('#dataGroup' + groups[x]).val());
                            $('#acceptGroup' + groups[x]).val($('#dataGroup' + groups[x]).val());
                        }
    
                    }
                    $('#acceptGroups').val($('#groups').val());
                    
                    
                    //popup the acceptance dialogue
                    $(target).overlay({
                                    effect: 'apple',
                                    speed: 'fast',
                                	expose: {
                                		color: '#000',
                                		loadSpeed: 200,
                                		opacity: 0.5
                                	},
                                    //close: '.wrapButtons .cancelButton',
                                    onLoad: function(){ 
                                       $('#decline').bind('click',function(e){
                                            e.preventDefault();
                                            $(target).overlay().close();
                                          }); //end bind to close dialogue
                                       $('a.info').bind('click',function(e){
                                       
                                       
                                                e.preventDefault();
                                                var newTarget='#ajaxPopup' 
                                                var url=$(this).attr('href').replace('z-','z-_'); 
                                                var errorURL=$(this).attr('href');
                                                
                                              $(newTarget).load(url, function(response, status, xhr){      
                                                         if (status=='error')
                                                         { // handle error messaging here
                                                            // if in development environment we redirect to the url so we can get an idea of what the problem is
                                                            //alert("error")
                                                            window.location.href=errorURL
                                                            
                                                         }
                                                         else
                                                         {
                                                         // alert("here");
                                                         //overlay dialogue
                                                                 $(newTarget).overlay({
                                                                            effect: 'apple',
                                                                            speed: 'fast',
                                                                        	expose: {
                                                                        		color: '#000',
                                                                        		loadSpeed: 200,
                                                                        		opacity: 0.5
                                                                        	},
                                                                            //close: '.wrapButtons .cancelButton',
                                                                            onLoad: function(){ 
                                                                               $('#closePanel').bind('click',function(e){
                                                                                    e.preventDefault();
                                                                                    $(newTarget).overlay().close();
                                                                                  }); 
                                                                            }, 
                                                                        	closeOnClick: false,
                                                                            api: true
                                                                        	
                                                                        }).load();
                                                         }
                                                 });//end load
                                       
                                       
                                       
                                       
                                       
                                       });   //end bind to any links within the dialogue
                                          
                                          
                                    }, 
                                	closeOnClick: false,
                                    api: true
                                	
                                }).load();                    
                    
                    
                 }//end test for error in response
     });//end load
     return false;
}


function digitTabbing(){
    $('input.digit').keyup(function(e){
        var n=parseInt($(this).attr('id').replace('digit',''));
        if (n!=13){
            n++
            $('#digit' + n).focus();
        }
        else{
            $('#continue').focus();
        }
    });

}

function checkOther(paramID){
    if ($('#' + paramID).val().toLowerCase().indexOf('other')!=-1){
        $('#' + paramID + 'wrap').show();
        $('#' + paramID + 'other').focus();
        
    }
    else{
        $('#' + paramID + 'wrap').hide();
    }

}

