/* 
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);
    
    if ($('#map').length){
        eval('load_map();');
    }
    if ($('#largeMap').length){
        eval('load_largeMap();');
    }
    

    $("a", "#useful_links").bind("click", function(event){  
          // event.preventDefault();
           var href=$(this).attr("href")  
           if (href.indexOf('javascript') == -1 ){ 
           var n_ref="javascript: update_content('" + href.replace('-z-','-z-_') + "');"
            $(this).attr("href",n_ref);
             }  
           
           });


    
    outbound_links()
    //pickup_gallery();
    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');
        }
    }
    
     if ($("#browsable").length){
    	 $("#browsable").scrollable({
            size: 6
         }).navigator().circular().autoscroll({ 
                steps: 1, 
                interval: 3000         
            });
            
         setup_images();
     } 
    
    
    
}


function setup_images(){
$(".items img").click(function() {
 
	// calclulate large image's URL based on the thumbnail URL 
	var url = $(this).attr("src").replace("thumb_", "");
 
	// get handle to element that wraps the image and make it semitransparent
	var wrap = $("#image_wrap").fadeTo("medium", 0.5);
 
	// the large image 
	var img = new Image();
 
	// call this function after it's loaded
	img.onload = function() {
 
		// make wrapper fully visible
		wrap.fadeTo("medium", 1);
 
		// change the image
		wrap.find("img").attr("src", url);
 
	};
 
	// begin loading the image 
	img.src = url;
 
// when page loads simulate a "click" on the first image
}).filter(":first").click();

}



//outbound_links: ensure that outbound links open in a new window
function outbound_links(){
    $("a", "#content").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 pickup_gallery(){
   $("a", "#gallery_items").bind("click", function(event){  
    event.preventDefault();

      var b=$('#u_base').val();
      var h=$(this).attr('id').toString().replace('href','media');
      //
      //alert(h)
      var img=$('#' + h).attr('src').replace('gallery','snapshot');
      //alert(img);
      $('#gallery_image').attr('src',img)  
      $('#gallery_strap').text($('#' + h).attr('alt'));
   });
}


//      fix_height: ensure that page reaches to bottom of the viewport
function fix_height(){
 
    var h=$(window).height()-199
    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.1234957740186;
    var lon=-9.289627075195312;
    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>Aloha Surf School</strong><br/>Fanore<br/>Co. Clare<br/>Ireland<br/>+353 87 2133 996<br/><br/>'
        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
    }
 }
 
 //  load_largeMap: populate and initialise Google map
function load_largeMap() {
//  alert("map")
    var lat=53.1234957740186;
    var lon=-9.289627075195312;
    var c_lat=53.10062087921428;
    var c_lon=-9.29443359375;
    if (GBrowserIsCompatible()) {
        var map = new GMap(document.getElementById("largeMap"));
        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>Aloha Surf School</strong><br/>Fanore<br/>Co. Clare<br/>Ireland<br/>+353 87 2133 996<br/><br/>'
        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);    
}




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

    //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 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: 750,
						timeout: 5000,
						type: 'sequence',
						containerheight: '336px'
					});
					$('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)
}



