/* 
janpro.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();});
$(window).bind('load',function(){eval('windowDependentRoutines();');});
//  setup_page: triggered when the page has completed loading
function setup_page(){
//activateMaps: initialise any google map objects
//activateBrowsables: initialise any scrollable galleries
    eval('activateBrowsables();');
//outbound_links: ensure that outbound links open in a new window
    eval('outbound_links();');
//      fix_height: ensure that page reaches to bottom of the viewport
    eval('fix_height();');
//activateNavigationMenu: enable superfish menu navigation
    eval('activateNavigationMenu();');
//enablePanels: enable sliding panels
    eval('enablePanels();');
//menuExpanders: bind a collapse/expand event to menu items
    eval('menuExpanders();');
//productLinks: bind to all product anchors
    eval('productLinks();');
       
//applyCSS: apply additional CSS effects & behaviours
    eval('applyCSS();');            
}

function windowDependentRoutines(){
    eval('activateMaps();');

}

//apresAjax: used to apply any styling etc. needed after an ajax load has completed
function apresAjax(){
    eval('activateBrowsables();');
    eval('applyCSS();');            
    eval('productLinks();');
}

//activateGallery: activate gallery object (if any)
function activateGallery(){
    if ($('#image_payload').length){  
        var buffer=$('#image_payload').val();
        var url=$('#u_base').val() + 'images/'
        if (buffer.lenght!=0){
            gallery=new make_gallery(url,buffer, 'gallery_image');
        }
    }
}
//activateMaps: initialise any google map objects
function activateMaps(){
    if ($('#map').length){
        eval('load_map("map");');
    }
    if ($('#large_map').length){
        eval('load_map("large_map");');
    }
}
//activateBrowsables: initialise any scrollable galleries
function activateBrowsables(){
     if ($("#browsable").length){
    	 $("#browsable").scrollable({
            size: 3
         }).navigator().circular().autoscroll({ 
                steps: 1, 
                interval: 3000         
            });
            
         setup_images();
     } 
}
//activateNavigationMenu: enable superfish menu navigation
function activateNavigationMenu(){
    jQuery('ul.sf-menu').supersubs({ 
            minWidth:    2,   // minimum width of sub-menus in em units 
            maxWidth:    24,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish();  // superfish();
}
//enablePanels: enable sliding panels
function enablePanels(){
    //Full Caption Sliding (Hidden to Visible)
    $('.panel').hover(function(){
    	$(".panelNote", this).stop().animate({top:'80px'},{queue:false,duration:460});
    }, function() {
    	$(".panelNote", this).stop().animate({top:'189px'},{queue:false,duration:160});
    });

}

//menuExpanders: bind a collapse/expand event to menu items
function menuExpanders(){
    if ($('.lhsWrap').length){
        $('.lhsWrap ul li ul').each(function(){
            if ($(this).attr('class')!='on'){
                $(this).hide();
            }
        });

            $('.lhsWrap a').bind('click',function(e){
                e.preventDefault();
                
                if ($(this).data('open')==1){
                    $(this).data('open',0)
                }
                else{
                    $(this).data('open',1)
                
                }
                var href=$(this).attr('href');
                var ajaxCandidate=false;
                if (href.indexOf('department')!=-1){
                        if ($(this).next('ul').has('li').length){
                            $(this).next('ul').slideToggle("fast");
                            href=href.replace('-z-','-z-_');
                            if (($('.lhsWrap').data('currenhref')!=href)){
                                $('.rhsWrap').toggleClass('working');
                                $('.rhsWrap').load(href,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=href;
                                        
                                     }                
                                     $('.rhsWrap').toggleClass('working');
                                     eval('apresAjax();');
                                     //enablePanels();
                                     
                                });   
                            }
                        }
                        else{
                          href=href.replace('-z-','-z-_'); 
                            if (($('.lhsWrap').data('currenhref')!=href)){
                                $('.rhsWrap').toggleClass('working');
                                //alert(href);
                                $('.rhsWrap').load(href,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=href;
                                        
                                     }                
                                     $('.rhsWrap').toggleClass('working');
                                     eval('apresAjax();')
                                     //enablePanels();
                                     
                                });   
                            }
                        }
                }//testing if ajaxCandidate
                else{
                    window.location.href=href;  
                }
                $('.rhsWrap').data('currenhref',href);
            });
      }//end check if lhsWrap on page
}

//applyCSS: apply additional CSS effects
function applyCSS(){
    //wrapItems table: adds class to every row
    if ($('.wrapItems').length){
        $('.wrapItems tbody td').addClass('topBorder');
    }
    //monitor listbox change (if applicable)
    if ($('#countryid').length){
        if ($('#countryid').attr('type')=='select-one'){
            $('#countryid').bind('change',function(){
                var href=$('#u_base').val() + 'shopping-z-_states-country-' + $(this).val() + '-address-' + $('#address4').val() + '.htm'
                //window.location.href=href;
                $('#stateList').load(href);
            });
        }
    }
    //user form elements: add onfocus/onblur behaviour
        $(':input').each(function( e, item ){
           var elementClassName=$(this).attr('class');
           switch(elementClassName){
                case '': // no class specified so ignore
                    break;
                default: //follow focus / blur events
                    $(this).focus(function(){
                        $(this).closest('tr').toggleClass('focused');
                    });
                    $(this).blur(function(){
                        $(this).closest('tr').removeClass('focused');
                    });
           }
        });
     //deal with related item links
     if ($('.wrapRelated').length){
        $(".wrapRelated a").bind('click',function(e){
            e.preventDefault();
            var href=$(this).attr('href').replace('-z-','-z-_');
            $(".wrapThumbnail").removeClass('on');
            $(this).parent().addClass('on');
            //window.location.href=href;
            //return void[0];
            $('.wrapListing').load(href,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=href;
                                        
                                     }                
                                     $('.rhsWrap').toggleClass('working');
                                     });
    
        });   
     }
}

//productLinks: bind to all product anchors
function productLinks(){
//bind to product information links    
    $("td.item a").bind('click',function(e){
        e.preventDefault();
        var href=$(this).attr('href').replace('-z-product','-z-_product');
        productInformation(href);
    
    });        
//bind to product information links in listing    
    $("td.info a").bind('click',function(e){
        e.preventDefault();
        var href=$(this).attr('href').replace('-z-product','-z-_product');
        productInformation(href);
    
    });        

//bind to product information links    
    $(".featurePanel a").bind('click',function(e){
        if ($(this).attr('href').indexOf('z-product') !=-1){
            e.preventDefault();
            var href=$(this).attr('href').replace('-z-product','-z-_product');
            productInformation(href);
        }    
    }); 
}
//expandCollapse: less/more expand & collapse
function expandCollapse(paramEl){
    //alert(paramEl.parent().attr('tagName'));
     if (paramEl.text()=='more'){
            paramEl.parent().slideUp('fast')
            paramEl.parent().parent().siblings('ul').toggle('fast');
        }
    else
        {
            paramEl.parent().parent().siblings().find('a.expander').parent().slideDown('fast');
            paramEl.parent().parent().toggle('fast',function(){
            });
    }
}


//productInformation: popup overlay
function productInformation(href){

    
    
//setup the dialogue caption
    $('#results').load(href, function(){
        
//display the modal dialogue
    $("#results").overlay({
        	// some expose tweaks suitable for facebox-looking dialogs
            effect: 'apple',
            speed: 'fast',
            
        	expose: {
        		// you might also consider a "transparent" color for the mask
        		color: '#000',
        		// load mask a little faster
        		loadSpeed: 200,
        		// highly transparent
        		opacity: 0.5
        	},
        	// disable this for modal dialog-type of overlays
        	closeOnClick: true,
            close: $('.wrapClose a'),
            onLoad: function(){
                $('.wrapClose a').bind('click',function(){
                                            $("#results").overlay().close();
                }); //end bind to closing element
                //prepare enlarge image
                $('a.zoom').bind('click',function(e){
                    //alert("zoom click");
                    e.preventDefault();
                    //$('#productImageGallery').slideToggle('slow');
                    $('#productImageGallery').fadeIn("slow");
                });//end bind to zoom                       
                $('a.zoomed').bind('click',function(e){
                    //alert("zoom click");
                    e.preventDefault();
                    //$('#productImageGallery').slideToggle('slow');
                    $('#productImageGallery').fadeOut("slow");
                });//end bind to zoom                       
            },//end on load
        	// we want to use the programming API
        	api: true
        // load it immediately after the construction
        }).load();
 });   
return false;

}
























//outbound_links: ensure that outbound links open in a new window
function outbound_links(){
    $("a", "#page_container").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);
         }
    });     
    
}


//      fix_height: ensure that page reaches to bottom of the viewport
function fix_height(){
 
    var h=$(window).height()-413
    var d=$(document).height()-413
    if (d > h){h=d}
    if (($('div.www_content').height()) < h){
       $('div.www_content').height(h);
    }
    else{
       $('div.www_content').height('auto');    
    }
    
    
}

//  load_map: populate and initialise Google map
function load_map() {

    
    var lat=54.00643836991847;
    var lon=-6.406724452972412;
    var myLatlng = new google.maps.LatLng(lat,lon);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("map"), myOptions);
                //create marker
                    var marker = new google.maps.Marker({
                          position: new google.maps.LatLng(parseFloat(lat),parseFloat(lon)), 
                          map: map,
                          icon: "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png",
                          title: 'R.Q. O\'Neill'
                           });
                                     


        return void[0];    
           
    
 }



//  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,'janpro',settings);    
}




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 validateEnquiry(){
//    alert('here');
    
    //txt_name
    if ($('#your_name').val().length==0){
        alert("Please enter a contact name!");
        $('#your_name').focus();
        return false;
    }
    //email address
    if ($('#your_email').val().length==0){
        alert("Please enter a contact email address!");
        $('#your_email').focus();
        return false;
    }
    var e=$('#your_email').val();
    if (!check_email(e,true)){
        alert("Please check that you have entered a valid  email address!");
        $('#your_email').focus();
        return false;
    }
    
    //telephone
    var telephone=fix_telephone($('#your_telephone').val());
    $('#your_telephone').val(telephone);
    
    if (telephone.length==0){
        alert("Please enter a contact telephone number!");
        $('#your_telephone').focus();
        return false;
    }

    //message
    if ($('#your_message').val().length==0){
        alert("Please tell us how we can assist!");
        $('#your_message').focus();
        return false;
    }
    
    if ($('#newsletteroption').attr('checked')==false){
        $('#reference').val('Do not add this customer to the mailing list!');
    }
    $('#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;   
}


//validateReminder: validate the password reminder dialogue
function validateReminder(){
//user_name
   if (jQuery.trim($('#user_name').val()).length==0){
        show_error_message("please enter your email address!",'error_message_panel');
        $('#user_name').focus();
        return false;
    }
//validate email address
    var e=jQuery.trim($('#user_name').val())
	if (!check_email(e,true)){
		show_error_message("The email address you have entered seems to be invalid, please correct your entry !",'error_message_panel');
        $('#user_name').focus();
		return false;
	}
        


//reminder_details 
$('#reminder_details').val('');
    return true;
 }
 
 
 
 function manage_flash(e){
 if (e==0){
     $('div.flash_object').hide();
 }
 else
 {      if ($('div.sf-wrapper ul li ul').css('display')=='block'){return void[0];} 
        $('div.flash_object').show();   }
}  


//validateSearch:
function validateSearch(){
    if (jQuery.trim($('#searchKeywords').val()).length==0){
        show_error_message("Please enter a value to search for before proceeding !",'error_message_panel');
        $('#searchKeywords').focus();
        return false;
    }
    return true;
}




