/* 
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      
*/
//  setup_page: triggered when the page has completed loading
function setup_page(){
   //alert("settings")
    if ($('#map').length){
        eval('load_map();');
    }
    

    $('#search_form').submit(
        function(){
        return eval('validate_search();')
        });
        
    if ($('#cv_form').length)
    {
        $('#cv_form').submit(
            function(){
            return eval('validate_cv();')
            });
    }
    
     if ($('#form_contact_us').length){
       // setup_focus();
        $('#form_contact_us').submit(
            function(){
            return eval('validate_form();');
            });
     }
     if ($('#login_error').length){
        window.setTimeout("$('#login_error').slideUp();",3000);
     }
    $('ul#animated_services').innerfade({
        speed: 2000,
        timeout: 10000,
        type: 'random_start',
        containerheight: '200px'
    });
    
    pickup_panels();
    enable_stats();
    dhtml_product_details();
    if ($('#launch_message').length){
        window.setTimeout("$('#launch_message').slideUp();",8000);
    }
    fix_height();
}


// pickup_panels: pickup home page panels
function pickup_panels(){
    $("div.home_panel", "#main_panel").bind("click", function(event){  
          // event.preventDefault();
          var id=this.id
          var e='#' + id + '_url'
          var href=$('#' + id + '_url').val();
          record_stat("promo",id.replace('panel_',''));
          window.location.href=href;
           });
  
}
//enable_stats: intercept (without interfering) any group or product links
function enable_stats(){
  $("a", "#sales_group_shortcuts").bind("click", function(event){  
          // event.preventDefault();
          var id=this.id
          record_stat("sales",id.replace('group',''));
           });  
  $("a.more", "#main_panel").bind("click", function(event){  
          // event.preventDefault();
          var id=this.id
          record_stat("product",id.replace('product',''));
           });  
}


function record_stat(param_context,param_id){
var a_url=$('#u_base').val() + "asp/fanore.asp";
var a_data="action=_stat&context=" + param_context + "&contextid=" + param_id
//alert(a_data)
$.ajax({
   type: "GET",
   url: a_url,
   data: a_data
 });
    

}
//offer_details: popup a div with details of this months special offer
function offer_details(param_record){
    url=$('#u_base').val() + "-z-promotion-recordid-" + param_record + '.htm'
    $('#utility').hide();
    $("#utility").load(url,'',function(){
        var cssObj = {
        'position' : 'absolute',
        'z-index' : '300',
        'left' : '300px',
        'top' : '200px'
      }
       $('#utility').css(cssObj);

        $('#utility').fadeIn(1000);
        window.setTimeout("$('#utility').fadeOut(1000);",5000);
    });

}
//      fix_height: ensure that page reaches to bottom of the viewport
function fix_height(){
 
    var h=$(window).height();
    if (($('#main_panel').height()) < h){
       $('#main_panel').height(h);
    }
    else{
       $('#main_panel').height('auto');    
    }
}

//  load_map: populate and initialise Google map
function load_map() {
//  alert("map")
    var lat=53.31640310326474;
    var lon=-6.333467960357666;
    var c_lat=53.342763063131976;
    var c_lon=-6.291046142578125;
    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), 10);
        //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>Abacus Systems & Networks</strong><br/>Unit 2-3, Mulcahy Keane Estate<br/>Greenhills Road<br/>Walkinstown, Dublin 12'
        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,'ggl',settings);    
}

//  validate_search: tests the search dialogue before posting
function validate_search(){
    if ($('#txt_keywords').val().length==0){
        alert("please enter one or more keywords or a product code to perform a search!");
        $('#txt_keywords').focus();
        return false;
    }
    $('#search_details').value="";
    
   return true;
}

// validate_customer_login: tests the payload of customer login form before posting
function validate_customer_login(param_main){
    var e=$('#user_name').val();
    var p=$('#user_pass').val();
    if (e.length==0){
        show_error_message("please enter your email address",'error_message_panel');
        $('#user_name').focus();
        return false;
    }
    //check that this is in supported format
    if (!check_email(e,true)){
        show_error_message("please check your email address as it does not seem to be valid",'error_message_panel');
        $('#user_name').focus();
        return false;
    }
    //check that password has been entered
    if (p.length==0){
        show_error_message("please enter your password",'error_message_panel');
        $('#user_pass').focus();
        return false;
    }
    //check that password conforms
    if (p.length<6){
        show_error_message("Your password should be at least 6 characters long",'error_message_panel');
        $('#user_pass').focus();
        return false;
    
    }
    if (p.length> 10){
        show_error_message("Your password should be no longer than 10 characters long",'error_message_panel');
        $('#user_pass').focus();
        return false;
    }
    $('#user_details').val('');
    return true;
}

//validate_reminder: test that a validly structured email address has been entered in password reminder dialogue
function validate_reminder(){
    var e=$('#user_name').val();
    if (e.length==0){
        show_error_message("please enter your email address",'error_message_panel');
        $('#user_name').focus();
        return false;
    }
    //check that this is in supported format
    if (!check_email(e,true)){
        show_error_message("please check your email address as it does not seem to be valid",'error_message_panel');
        $('#user_name').focus();
        return false;
    }
    $('#reminder_details').val('');
    return true;
}

// check_basket: validate shopping basket before posting
function check_basket(param_checkout){
    var buffer=$('#items').val();
    var array_items=buffer.split(",");
    var qty=""
    for (var i=0;i<array_items.length;i++){
        var q=$('#quantity' + array_items[i]).val();
        if (q.length==0){
            show_error_message("Please enter a valid quantity!",'error_message_panel');
            $('#quantity' + array_items[i]).focus();
            return false;
        }
        if (isNaN(q)){
            show_error_message("Please enter only whole numbers in the quantity!",'error_message_panel');
            $('#quantity' + array_items[i]).focus();
            return false;
        }
        if (parseInt(q)==0){
            show_error_message("Please enter a valid quantity, to remove an item click on the red 'x' !",'error_message_panel');
            $('#quantity' + array_items[i]).focus();
            return false;
        
        }
        if (qty.length!=0){
            qty+=',' 
        }
        qty+= q
    }
    var b_checked=$('#for_collection').attr('checked');
    if (b_checked==true){
        var f=1;
    }
    else{
        var f=0;
    }
    if (param_checkout==0){
        $('#uids').val(buffer);
        $('#qty').val(qty);
        $('#forcollection').val(f);
    }
    else{
        $('#checkuids').val(buffer);
        $('#checkqty').val(qty);
        $('#checkforcollection').val(f);
    
    }
    return true;

}

//empty_basket: double check that user wants to empty their shopping basket
function empty_basket(){
    if (confirm("Are you sure you want to delete your shopping basket?")){
        return true;
    }
    return false;
}

// 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
    var t=fix_telephone($('#txt_telephone').val());
    $('#txt_telephone').val(t)
    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;
}

//record_po: capture the purchase order number (if any)
function record_po(param_el){
    var p=$('#purchase_order').val()
    $('#' + param_el).val(p);
    return true;
}
//print_order: force new window
function print_order(){
   // $('#print_form').attr('target','_blank');
    //print();
    return false;
}


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_name').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 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;   
}




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;
}




//check_format: of a file
function check_format(param_value, param_type){

            
 if (param_value.length!=0){
        //check for allowed file types
        var s_ext=param_value.substr(param_value.length-3,3).toLowerCase();
        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;
        }
}

return false;
}
//confirm_logout: double check that user wishes to log out
function confirm_logout(){
    if (confirm("Are you sure you wish to log out?")){
        window.location.href=$('#u_base').val() + "-z-home-action-logout.htm"
    }
    return void[0];
}

//dhtml_product_details: trap product images and enable mouseover/ajax view of product details panel
function dhtml_product_details(){
    if ($('#category_list_products').length){
        $('img.product_thumbnail','#category_list_products').bind('mouseover',function(){
            var img=$(this).attr('id');
            var url=$('#u_base').val() + "-z-_product-recordid-" + img.replace('img','') + ".htm";
            record_stat("product",img.replace('img',''));
           // alert($(this).position().left);
            //var ileft=$(this).position().left;
            $('#utility').hide();
            $("#utility").load(url,'',function(){
                var cssObj = {
                'position' : 'absolute',
                'z-index' : '300',
                'left' : '300px',
                'width' : '500px',
                'top' : '200px'
              }
               $('#utility').css(cssObj);
        
                $('#utility').fadeIn(1000);
                window.setTimeout("$('#utility').fadeOut(1000);",5000);
            });
            
        });
        
    
    }
}


//cancel_order: confirm that user wishes to cancel their order
function cancel_order(){
   if (confirm("Are you sure you want to cancel this order ?")){
    return true;
   }
   return false;
}

//validate_password_update: validate that password conforms to business rules
function validate_password_update(){
    //user_pass
    var p=$('#user_pass').val();
    //check that password has been entered
    if (p.length==0){
        show_error_message("please enter your current password (this was sent to you when you registered)",'error_message_panel');
        $('#user_pass').focus();
        return false;
    }
    //check that password conforms
    if (p.length<6){
        show_error_message("Your password should be at least 6 characters long",'error_message_panel');
        $('#user_pass').focus();
        return false;
    
    }
    if (p.length> 10){
        show_error_message("Your password should be no longer than 10 characters long",'error_message_panel');
        $('#user_pass').focus();
        return false;
    }
    //new_user_pass
    var n=$('#new_user_pass').val();
    //check that password has been entered
    if (n.length==0){
        show_error_message("Please enter your new password",'error_message_panel');
        $('#new_user_pass').focus();
        return false;
    }
    //check that password conforms
    if (n.length<6){
        show_error_message("Your new password should be at least 6 characters long",'error_message_panel');
        $('#new_user_pass').focus();
        return false;
    
    }
    if (n.length> 10){
        show_error_message("Your new password should be no longer than 10 characters long",'error_message_panel');
        $('#new_user_pass').focus();
        return false;
    }
    
    //confirm_user_pass
    var c=$('#confirm_user_pass').val();
    if (c.length==0){
        show_error_message("Please re-enter your new password",'error_message_panel');
        $('#confirm_user_pass').focus();
        return false;
    }
    //check that new and confirm match
    if (c.toLowerCase()!=n.toLowerCase()){
        show_error_message("Please check your entry, the new password and confirm password entries do not match!",'error_message_panel');
        $('#new_user_pass').focus();
        return false;
    }
    return true;
    
}
