/* 
crann.js: library of javascript for animation / branding effects
    david.kelly@fanore.com (http://www.fanore.com/website_design.htm)
    
    
    
*/

function setup_page(){
   //alert("settings")
    if ($('#map').length){
        eval('load_map();');
    }
    if ($('#apple').length){
//        $("#apple img[rel]").overlay({effect: 'apple'}); 
    }
    
    if ($('#gallery_image').length){    
        var buffer=$('#image_payload').val();
        var url=$('#u_base').val() + 'shared/'
        gallery=new make_gallery(url,buffer, 'gallery_image');
    }
    $('#search_form').submit(
        function(){
        return eval('validate_search();')
        });
    
    if ($('#subscribe_email').length){
        //alert("here")
        $("#subscribe_email").bind("click", function(event){
           if ($('#subscribe_email').val()=='enter email address'){
            $('#subscribe_email').val('');
           } 
        });
    }    
    if ($('#quick_kw').length){
        //alert("here")
        $("#quick_kw").bind("click", function(event){
           if ($('#quick_kw').val()=='By Keyword'){
            $('#quick_kw').val('');
           } 
        });
    }    

    
     
    outbound_links();
    billing();
    paging();
    lhs_menu();
    setup_search();
    fix_height();
}

//setup_search: use Ajax to populate search dialogue listboxes
function setup_search(){

    $('#search_countries').bind("change", function(event){
           // re-populate search_distilleries
           var d=new Date();
           var url=$('#u_base').val() + 'asp/fanore.asp?z=_search_distilleries&country=' + $('#search_countries').val() + '&d=' + d 
            $('#distillery_listing').html($('#small_progress_bar').html());
            $("#distillery_listing").load(url,'',
                function(responseText)
                {
                $('#distillery_listing').html(responseText);
                eval('setup_search();')
                }
             );
             var url=$('#u_base').val() + 'asp/fanore.asp?z=_search_brands&country=' + $('#search_countries').val() + '&d=' + d 
           // re-populate search_brands
            $('#brand_listing').html($('#small_progress_bar').html());
            $("#brand_listing").load(url,'',
                function(responseText)
                {
                $('#brand_listing').html(responseText);
                eval('setup_search();')
                }
             );
           
        });
        
        
        
        
    $('#search_distilleries').bind("change", function(event){
    var d=new Date();
             var url=$('#u_base').val() + 'asp/fanore.asp?z=_search_brands&country=' + $('#search_countries').val() + '&distillery=' + $('#search_distilleries').val() + '&d=' + d 
           // re-populate search_brands
            $('#brand_listing').html($('#small_progress_bar').html());
            $("#brand_listing").load(url,'',
                function(responseText)
                {
                $('#brand_listing').html(responseText);
                eval('setup_search();')
                }
             );
    
    });

}

//check_search: check search dialogue before submitting
function check_search(){
    var b_return=false;
    if (parseInt($('#search_countries').val()) > 0){b_return=true}
    if (parseInt($('#search_distilleries').val()) > 0){b_return=true}
    if (parseInt($('#search_brands').val()) > 0){b_return=true}
    if ($('#quick_kw').val()=='By Keyword'){
        $('#quick_kw').val('')
    }
    if ($('#quick_kw').val().length!=0){b_return=true}
    return b_return;
}

//outbound_links: ensure that outbound links open in a new window
function outbound_links(){
    $("a", "#main_panel").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);
        }
        else{
            if ((href.indexOf('.pdf')!=-1)&&(href.indexOf('javascript')==-1)){
            var n_ref='javascript: open_link(\'' + href + '\');';
            $(this).attr("href",n_ref);
            
            }
        }
    });     
    
}

//lhs_menu
function lhs_menu(){
    $("a.menu_item", "#lhs_menu").bind("click", function(event){  
          event.preventDefault();
          var id=$(this).attr('id').replace('m','submenu');
          $('ul', "#lhs_menu").removeClass('on');
          //$('a.menu_item','#lhs_menu').
          $('#' + id).toggleClass('on');
           });
           
/*
    $("a.menu_item", "#lhs_menu").bind("mouseenter", function(event){  
          event.preventDefault();
          var id=$(this).attr('id').replace('m','submenu');
          $('#' + id).slideDown(1000,function(){
                   //$("ul.on", "#lhs_menu").slideUp(1000);
                   $('#' + id).toggleClass('on');
                   });     
          });
      
*/

}
function fix_height(){
 
    var h=$(window).height()-199
    var d=$(document).height()-199
    if (($('#main_panel').height()) < h){
       $('#main_panel').height(h);
    }
    else{
       $('#main_panel').height('auto');    
    }
}


// paging: catch paging links and replace with ajax calls
function paging(){
    $("a", "div.paging").bind("click", function(event){  
          var href=$(this).attr('href');
          if (href.indexOf('z-catalogue') > -1){
            var n_ref=href.replace('z-catalogue','z-_catalogue');
          }
          if (href.indexOf('z-distillery') > -1){
            var n_ref=href.replace('z-distillery','z-_distillery');
          }
          if (href.indexOf('z-brand') > -1){
            var n_ref=href.replace('z-brand','z-_brand');
          }
          if (href.indexOf('z-promotion') > -1){
            var n_ref=href.replace('z-promotion','z-_promotion');
          }
          if (href.indexOf('z-country') > -1){
            var n_ref=href.replace('z-country','z-_country');
          }
          
          $(this).attr('href','javascript:page_products(\'' + n_ref + '\');');
          triggers.html($('#ajax_progress_bar').html()); 
          
           });
           
            var triggers = $("div.paging").overlay({ 
             
                // some expose tweaks suitable for modal dialogs 
                expose: { 
                    color: '#333', 
                    loadSpeed: 200, 
                    opacity: 0.9 
                }, 
             
                closeOnClick: false 
            });           
      }

function page_products(url){
$('#product_listing').load(url,'',function(){
    paging();
});
}
//validate_subscribe: validate the 'subscribe box' 
function validate_subscribe(){
$('#subscribe_email').val(jQuery.trim($('#subscribe_email').val()));
    if ($('#subscribe_email').val()=='enter email address'){
        alert("please enter your email address!");
        return false;
    }
    
    var e=$('#subscribe_email').val()
    if (e.length==0){
        alert("please enter your email address!");
        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;
    }
    window.location.href=$('#u_base').val() + 'subscribe-z-subscribe-e-' + e + '.htm'
    return false;
}


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();
    }
}

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);    
}

function validate_search(){
    if ($('#txt_keywords').val().length==0){
        alert("please enter one or more keywords to perform a search!");
        $('#txt_keywords').focus();
        return false;
    }
   // $('search_details').value="";
   // $('search_form').submit();
   return true;
}





function cws_form(){
//    alert('here');
    //txt_company
    
    //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;
    }
    $('#txt_email').val(jQuery.trim($('#txt_email').val()));
    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;
}



//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_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;
}


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 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
 });
}
 
//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: 1000,
						timeout: 6000,
						type: 'sequence',
						containerheight: '266px'
					});
					$('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)
}


//validate_reminder: test the password reminder dialogue before submitting
function validate_reminder(){
    //email address
    if ($('#user_name').val().length==0){
        alert("Please enter your email address!");
        $('#user_name').focus();
        return false;
    }
    $('#user_name').val(jQuery.trim($('#user_name').val()));
    var e=$('#user_name').val();
    if (!check_email(e,true)){
        alert("Please check that you have entered a valid  email address!");
        $('#user_name').focus();
        return false;
    
    }
    $('#reminder_details').val('');
    return true;         
    
}

//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;
    }
    $('#user_pass').val(jQuery.trim($('#user_pass').val()));
    p=$('#user_pass').val();
    //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;
    }
    $('#new_user_pass').val(jQuery.trim($('#new_user_pass').val()));
    n=$('#new_user_pass').val();
    //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').val(jQuery.trim($('#confirm_user_pass').val()));
    //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;
    
}

