/* 
torque.js: library of javascript for animation / branding / validation & effects
    david.kelly@fanore.com (http://www.fanore.com/website_design.htm)
    torque_login: validates the login form before posting
    torque_reminder: validates the password reminder dialogue (checking that user has entered an email address)
    torque_registration: validates the registration form that updates the users web profile
    check_new_user: check new user form (displayed on checkout page)
    billing_details: capture billing details for customer accounts
    cancellation: checks the 'cancellation comment' form - which is an optional feedback form
    check_participants: validates participants form - dynamic array of form items
    display_addressbook: popup the addressbook div
*/
var iContext=false;
var pausecontent=false; // global variable used for scrolling news area
function setup_page(){
    var el=get_el('cv_form');
    if (el){eval('enable_tab_tracking(\'cv_form\');');}

    var el=get_el('form_register');
    if (el){eval('enable_tab_tracking(\'form_register\');');}
    var el=get_el("scrolling_news");
    if (el){
        start_scroller();
    }
    outbound_links()
}

//outbound_links: ensure that outbound links open in a new window
function outbound_links(){
    var children=$A($('content_area').select('a'));
    var b=$('u_base').value;
    var e_click=function(el)
    {   
        if (((!el.href.include(b))&&(!el.href.include('javascript'))&&(!el.href.include('mailto'))&&(!el.href.include('../')))||(el.href.include('.pdf'))){
            el.href='javascript: open_link(\'' + el.href + '\');';
         }
    }     
    children.each(e_click);     
    return void[0];
    
}
function start_scroller(){
    var el=get_el("news_data_feed");
    pausecontent=new Array()
//pausecontent[0]='<a href="http://www.javascriptkit.com">JavaScript Kit</a><br />Comprehensive JavaScript tutorials and over 400+ free scripts!'
    
    if (el){
        var buffer=el.value;
        if (buffer.charAt(buffer.length - 1) == "|") buffer = buffer.substr(0,buffer.length - 1);
	    var news=buffer.split("|");
        for (var i=0;i < news.length;i++){
            var feed=news[i];
            if (feed.charAt(feed.length - 1) == "$") feed = feed.substr(0,feed.length - 1);
            var array_feed=feed.split("$");
            var html='<a class="news_headline" href="' + array_feed[2] + '">'+ array_feed[0] + '</a><a class="news_text" href="' + array_feed[2] + '">' + array_feed[1] + '</a>';
            pausecontent[i]=html;
        }
        new pausescroller(pausecontent, "scrolling_news", "", 4000)
        //alert(buffer);
    
    }
    
    
    return void[0];
}





//enable_tab_tracking: when displaying a form we set a highlight to indicate which 'line' a user has moved focus to
function enable_tab_tracking(param_el){
    var v=navigator.appVersion;
    if (v.toString().include('MSIE 6.0')){
        return void[0];
    }

    var cls_highlight='highlighted';
    var el=get_el('cls_highlight');
    if (el){
        cls_highlight=$('cls_highlight').value;
    }
    var children=$A($(param_el).select('input.input_element','select.input_element','textarea.input_element'));
   // alert(children.length);
    var evfocus=function(el)
    {   
        //alert(Rico);
         Event.observe(el,'focus',function(){
            var row_name='row_' + el.id;
            var r=get_el(row_name);
            if (r){
                if (!$(row_name).hasClassName(cls_highlight)){
                    $(row_name).toggleClassName(cls_highlight);
                }
            }
         });
         Event.observe(el,'blur',function(){
            var row_name='row_' + el.id;
            var r=get_el(row_name);
            if (r){
                $(row_name).toggleClassName(cls_highlight);
            }
         });
         //Rico.Corner.round(el.id);
    }
    children.each(evfocus);
   // $('save').focusFirstElement();
    
}



//display_addressbook: popup the addressbook div
function display_addressbook(record_id){
    icontext=record_id;

   $('addressbook').show();
   new Rico.Effect.SizeAndPosition('addressbook', 0, 10, 400, 400, 500, 20);
}
//torque_password: validate the 'change password' dialogue
function torque_password(){
    var el=get_el("txt_password");
    var el_confirm=get_el("txt_confirm");
    if (el.value.length==0){
        alert("please enter a password that is at least 6 characters long!");
        el.value="";
        el_confirm.value="";
        el.focus()
        return false;
        
    }
    if (el.value.length > 12) {
        alert("please enter a password that is no longer than 12 characters in length!");
        el.value="";
        el_confirm.value="";
        el.focus()
        return false;
    }
    if (el.value.length < 6) {
        alert("please enter a password that is at least 6 characters long!");
        el.value="";
        el_confirm.value="";
        el.focus()
        return false;
    }
    var m=el.value;
    if (!string_syntax(m,false)){
        alert("the password that you have entered contains invalid characters, only letters and numbers are supported!");
        el.value="";
        el_confirm.value="";
        el.focus();
        return false;
    }
    if (!password_conforms(m)){
        alert("the password that you enter must contain at least one letter and number!");
        el.value="";
        el_confirm.value="";
        el.focus();
        return false;
    
    }
    var c = el_confirm.value;
    if (c!=m){
        alert("the password and confirm password values that you have entered do not match, please re-enter both values!");
        el_confirm.value="";
        el.value="";
        el.focus();
        return false;
    
    }
    return true;
    
}

//string_syntax: validates a string input
function string_syntax(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;

}

//password_conforms: validate that password entered by user conforms to password policy
function password_conforms(value){
    var alpha_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var numeric_chars="1234567890";
    var has_alpha=false;
    var has_number=false;
    for (var i=0;i<value.length;i++){
        //alert(alpha_chars.indexOf(value.substr(i,1)));
        if (alpha_chars.indexOf(value.substr(i,1))>-1){
            has_alpha=true;
        }
    }
   // alert(has_alpha);
    for (var i=0;i<value.length;i++){
        if (numeric_chars.indexOf(value.substr(i,1))>-1){
            has_number=true;
        }
    }
    if ((has_alpha)&&(has_number)){
        return true;
    }
    else{
        return false;
    }
    
}

function this_address(record_id){
    var prefix='copy_' + record_id + '_';
    var suffix='_' + icontext;
    var elname='';
    var elsource=false;
    var eldestination=false;
    
    elname='accountid';
    elsource=get_el(prefix + elname);
    eldestination=get_el(elname + suffix);
    if (eldestination.value==elsource.value){
        alert("you have already used this entry!");
        return void[0];
    }
    eldestination.value=elsource.value;
    elname='firstname';
    elsource=get_el(prefix + elname);
    eldestination=get_el(elname + suffix);
    eldestination.value=elsource.value;
    elname='surname';
    elsource=get_el(prefix + elname);
    eldestination=get_el(elname + suffix);
    eldestination.value=elsource.value;
    elname='title';
    elsource=get_el(prefix + elname);
    eldestination=get_el(elname + suffix);
    eldestination.value=elsource.value;
    elname='email';
    elsource=get_el(prefix + elname);
    eldestination=get_el(elname + suffix);
    eldestination.value=elsource.value;
    elname='telephone';
    elsource=get_el(prefix + elname);
    eldestination=get_el(elname + suffix);
    eldestination.value=elsource.value;
    $('link_' + record_id).href='javascript: void[0];'
   $('addressbook').hide();
   new Rico.Effect.SizeAndPosition('addressbook', 0, 100, 100, 30, 50, 2);
}

function hide_addressbook(){
   $('addressbook').hide();
   new Rico.Effect.SizeAndPosition('addressbook', 0, 100, 100, 30, 50, 2);

}
//cancellation: checks the 'cancellation comment' form - which is an optional feedback form 
function cancellation(){
//    var el=get_el("txt_subject");
//    if (el.value.length==0){
//        alert("please complete the form if you wish to submit your feedback!");
//        el.focus();
//        return false;
//    }
    //txt_detail
    var el=get_el("txt_detail");
    if (el.value.length==0){
        alert("please complete the form if you wish to submit your feedback!");
        el.focus();
        return false;
    }
    
    return true;

}
//handles searching the site
//ensures search terms are not ""
function torque_search(){
    var v=$F('search_keywords');
	
    if (v.strip().length==0){
        alert("please enter one or more words or phrases to search for!");
        return false;
    }
    return true;
}

// torque_login: validates the login form that is presented to customers
function torque_login(){
// check that username field has been populated


    if ($F('txt_username').blank()){
        alert("please enter your email address !");
        $('txt_username').focus();
        return false;
    }
    if ($F('txt_username')=="e-mail address"){
        alert("please enter your email address !");
        $('txt_username').value="";
        $('txt_username').focus();
        return false;
    
    }
    var s=$F('txt_username');
    if (!fixstring(s,true)){
        alert("the email address you have entered is not supported on this system, please check your entry!");
        $('txt_username').focus();
        return false;
    
    }
    
// check the password entry
    if ($F('txt_password').blank()){
        alert("please enter your password !");
        $('txt_password').focus();
        return false;
    }
    
    
    
return true;
}


function open_asset(param_asset,param_id){
    var url="../asp/ajax.asp"
    var params="recordid=" + param_id + "&action=log_access"
    var d=new Date();
    var myAjax = new Ajax.Updater('', url, {method: 'get', parameters: params + '&d=' + d.toString()});  
    open_link(param_asset);
}

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,'iitdpopup',settings);    
}



//check_returning: validating 'returning customer' dialogue
function check_returning(){
// check that username field has been populated
    var el=get_el("txt_user");
    if (el.value.length==0){
        alert("please enter your email address !");
        el.focus();
        return false;
    }
    if (el.value=="e-mail address"){
        alert("please enter your email address !");
        el.value="";
        el.focus();
        return false;
    
    }
    var s=el.value;
    if (!fixstring(s,true)){
        alert("the email address you have entered is not supported on this system, please check your entry!");
        el.focus();
        return false;
    
    }
    
// check the password entry
    var el=get_el("txt_pass");
    if (el.value.length==0){
        alert("please enter your password !");
        el.focus();
        return false;
    }
    
    
    
return true;

}


//torque_reminder: validates the password reminder dialogue (checking that user has entered an email address
function torque_reminder(){
// check that username field has been populated
    var el=get_el("txt_username");
    if (el.value.length==0){
        alert("please enter the email address you used before with this service!");
        el.focus();
        return false;
    }
    var s=el.value;
    if (!fixstring(s,true)){
        alert("the email address you have entered is not supported on this system, please check your entry!");
        el.focus();
        return false;
    
    }
return true;
    
}


// torque_registration: validates the registration form that updates the users web profile
function torque_registration(){
    var el=get_el("txt_email");
    if (el.value.length==0){
        alert("please enter the email address you wish to use with this service!");
        el.focus();
        return false;
    }
    var s=el.value;
    if (!fixstring(s,true)){
        alert("the email address you have entered is not supported on this system, please check your entry!");
        el.focus();
        return false;
    
    }
    return true;
}


//torque_resource: validate the protected resource registration form
function torque_resource(){
    if ($F('txt_name').blank()){
        alert("please enter your name!");
        $('txt_name').focus();
        return false;
    
    }
    if ($F('txt_email').blank()){
        alert("please enter your email address (your password will be sent to this address)!");
        $('txt_email').focus();
        return false;
    
    }
    var s=$F('txt_email');
    if (!fixstring(s,true)){
        alert("the email address you have entered is not supported on this system, please check your entry!");
        $('txt_email').focus();
        return false;
    }
    
    var telephone=fix_telephone($F('txt_telephone'));
    $('txt_telephone').value=telephone;
    if ((telephone.blank())||(telephone.length<6)){
        alert("Please enter either a valid telephone or mobile number in numeric format (e.g. 123456)!");
        $('txt_telephone').value='';
        $('txt_telephone').focus();
        return false;
    }

    
return true;
}

//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;   
}


//check_new_user: check new user form (displayed on checkout page)
function check_new_user(){
    var el=get_el("txt_email");
    if (el.value.length==0){
        alert("please enter the email address you wish to use with this service!");
        el.focus();
        return false;
    }
    var s=el.value;
    if (!fixstring(s,true)){
        alert("the email address you have entered is not supported on this system, please check your entry!");
        el.focus();
        return false;
    
    }
    return true;

}

//billing_details: capture billing details for customer accounts
function billing_details(){
    // company name
    var el=get_el("txt_company");
    if (el.value.length==0){
        alert("please enter your  company name!");
        el.focus();
        return false;
    }
    // first name
    var el=get_el("txt_firstname");
    if (el.value.length==0){
        alert("please enter your first name!");
        el.focus();
        return false;
    }
    // surname
    var el=get_el("txt_surname");
    if (el.value.length==0){
        alert("please enter your surname!");
        el.focus();
        return false;
    }
    // address line 1
    var el=get_el("txt_address1");
    if (el.value.length==0){
        alert("please enter a two line address!");
        el.focus();
        return false;
    }
    // address line 2
    var el=get_el("txt_address2");
    if (el.value.length==0){
        alert("please enter a two line  address!");
        el.focus();
        return false;
    }
//    // address line 3 ==city
//    var el=get_el("txt_address3");
//    if (el.value.length==0){
//        alert("please enter your city!");
//        el.focus();
//        return false;
//    }
//    // address line 4 == state
//    var el=get_el("txt_address4");
//    if (el.value.length==0){
//        alert("please enter your state!");
//        el.focus();
//        return false;
//    }
//    // post-code == zip code
//    var el=get_el("txt_postcode");
//    if (el.value.length==0){
//        alert("please enter your zip-code!");
//        el.focus();
//        return false;
//    }
    // username /email
    var el=get_el("txt_username");
    if (el.value.length==0){
        alert("please enter your email address (this is used for logging on to your web profile)!");
        el.focus();
        return false;
    }
    var m = el.value;
    if (!fixstring(m,true)){
        alert("the email address that you have entered contains characters that are not supported by our system please contact technical support!");
        el.focus();
        return false;
    
    }
    // confirm email address
    var el_confirm=get_el("txt_confirm");
    if (el_confirm.value != m){
        alert("your email address is critical for all actions on the web site, please confirm your email address");
        
        el_confirm.focus();
        return false;
        
    }

    // mobile number or telephone number is required
    var el=get_el("txt_mobile");
    var el_telephone=get_el("txt_telephone");
    
    if ((el.value.length==0) && (el_telephone.value.length==0)){
        alert("please enter either a mobile or landline number!");
        el.focus();
        return false;
    }
	else {
		//validate mobile no
		var str = el.value
		var chr = ""	
		var nDigits = 0
		for (position = 0; position < str.length; position++){
		   chr = str.charAt(position)
		   if (!(chr >= "0" && chr <= "9")){
		   		alert("please enter a mobile phone number that contains only numbers");
                el.value="";
				el.focus();
				return false;
		   }
		}
		
		var str = el_telephone.value
		var chr = ""	
		var nDigits = 0
		for (position = 0; position < str.length; position++){
		   chr = str.charAt(position)
		   if (!(chr >= "0" && chr <= "9")){
		   		alert("please enter a phone number that contains only numbers");
                el_telephone.value="";
				el_telephone.focus();
				return false;
		   }
		}
	}


//    // telephone number
//    var el=get_el("txt_telephone");
//    if (el.value.length==0){
//        alert("please enter a land line number!");
//        el.focus();
//        return false;
//    }
    return true;


}


//print_order: opens a new window ready for printing an order
function print_order(){
    var address='../asp/window.asp?z=print_order';
    var window_width=0;
    var window_height=0;
    var window_top=0;
    var window_left=0;
    
    // set width, height and positioning properties based on context
            window_width=600;
            window_height=600;
            window_top=0;
            window_left=0;
    var use_default=0; // over-ride default properties
    var k=open_new_window(address, 'order', use_default, window_width,window_height,window_top,window_left);
    return false;
}


// check_participants: validates participants form - dynamic array of form items
function check_participants(){
   // pickup the list of events
   var el=get_el("event_payload")
   var buffer=el.value;
   	if (buffer.charAt(buffer.length - 1) == ",") buffer = buffer.substr(0,buffer.length - 1);
	var event_data=buffer.split(",");
    for (var i=0;i<event_data.length;i++){
        var event_id=event_data[i];
        //alert(event_id);
        var el=get_el("payload_" + event_id);
        var payload=el.value;
        if (!validate_payload(payload, event_id)){
           // alert("validate payload failed");
			return false;
        }
        
    }
    return true;
	

}

// validate_payload: process an event payload
function validate_payload(buffer, record_id){
   	if (buffer.charAt(buffer.length - 1) == ",") buffer = buffer.substr(0,buffer.length - 1);
	var payload_data=buffer.split(",");
    for (var i=0;i<payload_data.length;i++){
        var uid=payload_data[i];
        //alert(uid);
        var title=get_el("title_" + uid);
        var firstname=get_el("firstname_" + uid);
        var surname=get_el("surname_" + uid);
        var email=get_el("email_" + uid);
        var telephone=get_el("telephone_" + uid);
        if (!validate_controls(title,firstname,surname,email,telephone, record_id, uid)){
            return false;
        }
    }
    return true;
}

//validate_controls: validate values of the passed controls
function validate_controls(title,firstname,surname,email,telephone, record_id, uid){

    // title
    if (title.value.length==0){
        alert("please enter this participant's job title!");
        title.focus();
        return false;
    }
    
    
    // firstname
    if (firstname.value.length==0){
        alert("please enter this participant's firstname!");
        firstname.focus();
        return false;
    }
    
    
    // surname
    if (surname.value.length==0){
        alert("please enter this participant's surname!");
        surname.focus();
        return false;
    }
    
    
    // email
    if (email.value.length==0){
        alert("please enter this participant's email address!");
        email.focus();
        return false;
    }
    
    var m = email.value;
    if (!fixstring(m,true)){
        alert("the email address that you have entered contains characters that are not supported by our system please contact technical support!");
        email.value="";
        email.focus();
        return false;
    
    }
	//alert("testing emails");
	var account_uid = get_el("account_uid")
	var el = get_el("copy_" + account_uid.value + "_email")
	//alert("comparing: " + m + " to: " + el.value) 
    var a=get_el("accountid_" + uid).value;
	if ((m == el.value)&&(account_uid.value != a)){
		//alert("executing this address");
		icontext=uid;
		this_address(account_uid.value);
	}
	
    
    // title
    if (telephone.value.length==0){
        alert("please enter this participant's telephone number!");
        telephone.focus();
        return false;
    }
    
    
    return true;

}


//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();
    }
}


//validate_cv: check that all required fields have been populated
function validate_cv(){
    //check the name
    var el=get_el("txt_name")
    if (el.value.length==0){
        alert("please enter your name !")
        el.focus();
        return void[0];    
    }
    
    //check the email address
    var el=get_el("txt_email")
    if (el.value.length==0){
        alert("please enter your email address !")
        el.focus();
        return  void[0];    
    }
    var sval=el.value
    // check email is correct format
	if (!fixstring(sval,true)){
		alert("Your email address is invalid this system only supports the format 'yourname@address.com' !");
		el.focus();
		return  void[0];
	}
        var telephone=fix_telephone($F('txt_telephone'));
        $('txt_telephone').value=telephone;
        if ((telephone.blank())||(telephone.length<6)){
            alert("Please enter either a telephone or mobile number in numeric format (e.g. 123456)!");
            $('txt_telephone').value='';
            $('txt_telephone').focus();
            return void[0];
        }
	
    //check the comment
    //var el=get_el("txt_comment")
    //if (el.value.length==0){
    //    alert("please tell us a bit about yourself and your availability !")
    //    el.focus();
    //    return  void[0];    
    //}

    if ($F('attachment').blank()){
       alert("Please submit an up to date resume!");
       return void[0];
    }
    if (!check_format('attachment', 'cv')){
        alert("Only files of the following format (jpg, gif, png, mdi,doc, docx, tif or PDF) can be accepted!");
        $('attachment').focus();
        return void[0];
    }
            
    var progress_bar_url=$F('progress_bar_url');
// display a window indicating save progress 
            var w=380;
            var h=50;
            var winLeft=Math.round((screen.width - w)/2);
            var winTop=Math.round((screen.height - h)/2);
            var sVersion = navigator.appVersion;
             
           if (sVersion.indexOf('MSIE') != -1 && sVersion.substr(sVersion.indexOf('MSIE')+5,1) > 4)
          {
        		var settings="dialogWidth:380px; dialogHeight:50px; center:yes";
        		var x=window.showModelessDialog(progress_bar_url+ '&b=IE',null,settings);
                x.opener=window
            }
            else
            {
        		//var x=window.open(progress_bar_url+ '&b=NN','','width=370,height=115', true);
                var x=window.open(progress_bar_url+ '&b=NN','','width=380px,height=50', true);
        
           }
           
            x.focus()
   
   

            

    var f=$('cv_form')
    f["cv_details"].value="";
    $('cv_form').submit();

}
//check_format: of a file
function check_format(param_el, param_type){

            var el=get_el(param_el)
            if (el){
                if (el.value.blank()){
                    return true;
                }
                var s_file=el.value;
                //alert(s_file);
                if (s_file.length!=0){
                    //check for allowed file types
                    s_ext=s_file.substr(s_file.length-3,3).toLowerCase();
                    if (param_type=='cv'){
                            switch(s_ext){
                                case "jpg": //ok
                                    return true;
                                    break;
                                case "gif":
                                    return true;
                                    break;
                                case "tif":
                                    return true;
                                    break;
                                case "pdf":
                                    return true;
                                    break;
                                case "mdi":
                                    return true;
                                    break;
                                case "doc":
                                    return true;
                                    break;
                                case "ocx":
                                    return true;
                                    break;
                                case "png":
                                    return true;
                                    break;
                            }
                    }
                    //switch
                }
            }            

return false;
}


