﻿/*
* Kajima xJavascript
* -------------------------
* J Barr
* -------------------------
* Core Lib
* rev 0.98.1
* 02.02.2010 
* -------------------------
*/

$(document).ready(function() {

    initQuickSearch();
    initFooter();
    $(".selectbox").selectbox();
    
    // SEO stuff 15.02.11
    $('#homeReadMo').hide( );
	$('a.homeReadMo').click( function(){
		if( document.getElementById( 'homeReadMo' ).offsetHeight > 0 ) {
			$( this ).html( 'read more &raquo;' );
			$( '#homeReadMo' ).slideUp( 'fast' );
		}
		else{
			$(this).html('&laquo; read less');
			$( '#homeReadMo' ).slideDown( 'fast' );
		}
		return false;
	});
	
    if ($(".fLogin").length) { initLogin(); }
    if ($(".fEnquiry").length) { initEnquiry(); }
    if ($(".fBooking").length) { initBooking(); }
    if ($(".fPayment").length) { initPayment(); }
    
    if ($(".rotating_images").length) { initRotatingImages(); }
    if ($("#sidebarmenu1").length) { initsidebarmenu(); }
   
    $(".datepicker").datepicker({dateFormat: 'dd/mm/yy'});
    
	$(".galleryOpener").prettyPhoto({ theme:'light_rounded' });
});

function showGallery(div) {

    $("#"+div).fadeIn("500");
    $("#"+div).parent().children(".overlay").fadeIn("500");

}

function hideGallery(div) {

    $("#"+div).parent().children(".overlay").fadeOut("500");
    $("#"+div).fadeOut("500");
}

function nextGalleryImage(id) {

    var images = $("#"+id).children(".gallery_image").toArray();
    
    var index = $(images).index($(".gallery_image:visible"));
    var length = $(images).length;
    
    if (index > -1 && index < length - 1) {
        $($(images).get(index)).hide();
        $($(images).get(index + 1)).fadeIn(1000);   
    }
    else if (index == length - 1) {
        $($(images).get(index)).hide();
        $($(images).get(0)).fadeIn(1000);  
    }
}

function initRotatingImages() {
    
    $.each($(".rotating_images"), function() {
        setTimeout("rotateImage(\"" + $(this).attr("id") + "\");", 10000);    
    });
}

function rotateImage(id) {

    var images = $("#"+id).children(".rotating_image").toArray();
    
    var index = $(images).index($(".rotating_image:visible"));
    var length = $(images).length;
    
    if (index > -1 && index < length - 1) {
        $($(images).get(index)).hide();
        $($(images).get(index + 1)).fadeIn(1000);   
    }
    else if (index == length - 1) {
        $($(images).get(index)).hide();
        $($(images).get(0)).fadeIn(2000);  
    }
    
    setTimeout("rotateImage(\"" + id + "\");", 10000);  
}

// initFooter
function initFooter() {

    $(".footerToggler").click(function() {
        $("#subfooter").toggle();
		window.scrollBy(0, 500);
    });
    
		
	$("#btnToggleEditor").click(function () {
		$("#subeditor").toggle();
		window.scrollBy(0, 0);
	});	
}

var topnav=function(){
	var t=15,z=50,s=6,a;
	function dd(n){this.n=n; this.h=[]; this.c=[]}
	dd.prototype.init=function(p,c){
		a=c; var w=document.getElementById(p), s=w.getElementsByTagName('ul'), l=s.length, i=0;
		for(i;i<l;i++){
			var h=s[i].parentNode; this.h[i]=h; this.c[i]=s[i];
			h.onmouseover=new Function(this.n+'.st('+i+',true)');
			h.onmouseout=new Function(this.n+'.st('+i+')');
		}
	}
	dd.prototype.st=function(x,f){
		var c=this.c[x], h=this.h[x], p=h.getElementsByTagName('a')[0];
		clearInterval(c.t); c.style.overflow='hidden';
		if(f){
			p.className+=' '+a;
			if(!c.mh){c.style.display='block'; c.style.height=''; c.mh=c.offsetHeight; c.style.height=0}
			if(c.mh==c.offsetHeight){c.style.overflow='visible'}
			else{c.style.zIndex=z; z++; c.t=setInterval(function(){sl(c,1)},t)}
		}else{p.className=p.className.replace(a,''); c.t=setInterval(function(){sl(c,-1)},t)}
	}
	function sl(c,f){
		var h=c.offsetHeight;
		if((h<=0&&f!=1)||(h>=c.mh&&f==1)){
			if(f==1){c.style.filter=''; c.style.opacity=1; c.style.overflow='visible'}
			clearInterval(c.t); return
		}
		var d=(f==1)?Math.ceil((c.mh-h)/s):Math.ceil(h/s), o=h/c.mh;
		c.style.opacity=o; c.style.filter='alpha(opacity='+(o*100)+')';
		c.style.height=h+(d*f)+'px'
	}
	return{dd:dd}
}();
	
if (document.getElementById("topnav") != null) {
    var topnav=new topnav.dd("topnav");
    topnav.init("topnav","menuhover");
}

var menuids=["sidebarmenu1"] //Enter id(s) of each Side Bar Menu's main UL, separated by commas

function initsidebarmenu(){
for (var i=0; i<menuids.length; i++){
  var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
    for (var t=0; t<ultags.length; t++){
    ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle"
  if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu
   ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
  else //else if this is a sub level submenu (ul)
    ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
    ultags[t].parentNode.onmouseover=function(){
    this.getElementsByTagName("ul")[0].style.display="block"
    }
    ultags[t].parentNode.onmouseout=function(){
    this.getElementsByTagName("ul")[0].style.display="none"
    }
    }
  for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
  ultags[t].style.visibility="visible"
  ultags[t].style.display="none"
  }
  }
}
    
// Login Form
function initLogin() {
    $(".fLogin").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: ".messageBox",
        debug: false,
        rules: {
            Username: { required: true },
            Password: { required: true }
        },
        messages: {
            Username: valLogin_Required_Username,
            Password: valLogin_Required_Password
        }
    }); 
}


// Enquiry Form
function initEnquiry() {
    $(".fEnquiry").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: ".messageBox",
        debug: false,
        rules: {
            FirstName: { required: true },
            LastName: { required: true },
            Email: { required: true, email: true },
            Telephone: { required: true },
            Text: { required: true }
        },
        messages: {
            FirstName: valEnquiry_Required_FirstName,
            LastName:  valEnquiry_Required_LastName,
            Email: { required: valEnquiry_Required_Email, email: valEnquiry_Invalid_Email },
            Telephone: valEnquiry_Required_Telephone,
            Text: valEnquiry_Required_Text
        }
    }); 
}

// Payment Form
function initPayment() {
    $(".fPayment").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: ".messageBox",
        debug: false,
        rules: {
            Agree: { required: true }
        },
        messages: {
            Agree: "Please agree to the terms and conditions by checking the box"
        }
    }); 
}


// Enquiry Form
function initBooking() {

    $("#ddlReferrer").change(function() {
        if ($("#ddlReferrer").val() == "Other") {
            $("#txtReferrerOther").show();
        } else {
            $("#txtReferrerOther").hide();
        }
    });
    
    $(".fBooking").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: ".messageBox",
        debug: false,
        rules: {
//            DateFrom: { required: true, dateITA: true },
//            DateTo: { required: true, dateITA: true },
            FirstName: { required: true },
            LastName: { required: true },
            Email: { required: true, email: true },
            Referrer: { required: true }
//            TelephoneDay: { required: true },
//            TelephoneNight: { required: true },
//            CompanyName: { required: true }
        },
        messages: {
//            DateFrom: { required: valBooking_Required_DateFrom, dateITA: valBooking_Invalid_DateFrom },
//            DateTo:  { required: valBooking_Required_DateTo, dateITA: valBooking_Invalid_DateTo },
            FirstName: valBooking_Required_FirstName,
            LastName:  valBooking_Required_LastName,
            Email: { required: valBooking_Required_Email, email: valBooking_Invalid_Email },
            Referrer: { required: "Please select where you first heard of us" }
//            TelephoneDay: valBooking_Required_TelephoneDay,
//            TelephoneNight: valBooking_Required_TelephoneNight,
//            CompanyName: valBooking_Required_CompanyName
        }
    }); 
}

// load flash movie
loadFlash = function(id, swf, height, vars) {
   var width = $("#" + id).width(); 
   var params = {
      }; 
   var attributes = {
      }; 
   params.menu = "false"; 
   params.quality = "high"; 
   params.wmode = "transparent"; 
   params.bgcolor = "#000000"; 
   params.allowFullScreen = "true"; 
   params.base = "."; 
   // using a slash '/' here breaks ie6
   params.salign = "tl"; 
   params.scale = "default"; 
   attributes.allowFullScreen = "true"; 
   attributes.id = id; 
   attributes.name = id; 
   swfobject.embedSWF(swf, id, width, height, "9.0.0", false, vars, params, attributes); 
}
   
// load flv video   
function loadVideo(id, video, img, title, ratio) {


   var width = $("#" + id).width(); 
   
   var height = parseInt(parseFloat(width) / parseFloat(ratio) + 25, 10);
   var params = {
      }; 
   var flashvars = {
      }; 
   var attributes = {
      }; 
   params.menu = "false"; 
   params.quality = "high"; 
   params.wmode = "transparent"; 

   params.allowFullScreen = "true"; 
   attributes.id = id; 
   attributes.name = id; 
   flashvars.movie = video;  
   flashvars.fgcolor= 0xEC7F32;			
   flashvars.bgcolor = 0x222222;
   flashvars.previewimage=img;
   flashvars.autoload = "on";
   //&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&previwimage=&autoload=on
   
   //'movie=video.flv&fgcolor=0×006AC3&bgcolor=0×000000&volume=70′
   swfobject.embedSWF("/swf/OSplayer.swf", id, width, height, "9.0.0", false, flashvars, params, attributes); 
}
   
// Google map
function loadMap(div, lat, lon, zoom, callback) {
	if (GBrowserIsCompatible()){
	    
	    map = new GMap2(document.getElementById(div));
        
	    map.addControl(new GSmallMapControl());
		map.addControl(new GScaleControl());
		map.setCenter(new GLatLng(lat, lon), zoom);
        
        if (typeof(callback) !== 'undefined') {
            callback();
        }
	}
}

function addMapMarker(lat, lon, info, theme) {

    var icon = new GIcon();
    icon.image = "/images/main/kajima_pointer_"+theme+".png";
    icon.iconSize = new GSize(40, 40);   
    icon.shadow = "/images/main/kajima_shadow.png";
    icon.shadowSize =  new GSize(40, 40);   
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    markerOptions = { icon:icon };
    
    var point = new GLatLng(lat, lon);
    var marker = new GMarker(point, markerOptions);

    if (info.toString().length > 1) {
        if (typeof (info) !== "undefined") {////////
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(info);
            });
        }
    }
    map.addOverlay(marker);
}

function addClickListener(txtLatitudeID, txtLongitudeID, txtZoomID) {

    // click event listener
    GEvent.addListener(map, 'click', function(overlay, point) {
        if (overlay) {
            map.removeOverlay(overlay);
        } else if (point) {
            map.clearOverlays(); 
            var marker = new GMarker(point);
            map.addOverlay(marker);         

            var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( point );
            if ( matchll ) { 
	            lat = parseFloat( matchll[1] );
	            lon = parseFloat( matchll[2] );
	            lat = lat.toFixed(6);
	            lon = lon.toFixed(6);
            } 
            $(txtLatitudeID).attr("value", lat);
            $(txtLongitudeID).attr("value", lon);
            $(txtZoomID).attr("value", map.getZoom());
        }
    });
}

// Google search
function loadSearch(id, qry) {
    var searchControl = new google.search.SearchControl();

    var options = new google.search.SearcherOptions();
    options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);

    // Add in a full set of searchers
    var searcher = new google.search.WebSearch();
    searcher.setSiteRestriction("www.kajima.co.uk");
    searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
    searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);

    searchControl.addSearcher(searcher, options);

    // Tell the searcher to draw itself and tell it where to attach
    searchControl.draw(document.getElementById(id));

    // Execute an inital search
    searchControl.execute(qry);
}
  
// search box
function initQuickSearch() {

    // cancel bubble
    $("#fQuickSearch").submit(function() { return false; });
    
    $("#fQuickSearch input[name='Submit']").click(function() {
        var search = $("#fQuickSearch input[name='SEARCH']").val();
        if (search !== $(this).attr("name")) {
            location.href = "/search/?qry=" + escape(search);
        }
    });
    
    $("#fQuickSearch input[name='SEARCH']").focus(function() {
        if ($(this).val() == $(this).attr("name")) {
            $(this).val("");
        }
    });
    
    $("#fQuickSearch input[name='SEARCH']").blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("name"));
        }
    });
    
    $("#fQuickSearch input[name='SEARCH']").bind('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) {
            var search = $("#fQuickSearch input[name='SEARCH']").val();
            location.href = "/search/?qry=" + escape(search);
        }
    });
}

runQuickSearch = function() {
    var search = $('#txtSearch').attr('value');
    location.href = "/" + lang + "/search/?qry=" + escape(search);
}
   
// toggle collapsible panels
setupTogglers = function() {
    $(".toggle").parent().click(function() {
        $(this).next(".collapsible").slideToggle("500"); 
        $(this).children(".toggle").children(".open").toggle();
        $(this).children(".toggle").children(".close").toggle();
    }); 
}
   
// Window popoup
popitup = function(url, width, height) {
    newwindow=window.open(url,"name","height=" + height + ",width=" + width + ",menubar=yes,resizable=yes,scrollbars=yes");
	if (window.focus) {
	    newwindow.focus();
	}
	return false;
}

// Call asp.net HttpHandler to process js requests
ajaxRequest = function(data, url, callback) {
    $.ajax({ url: url,  
        type: "POST",
        cache: false,
        data: data,
        dataType: "json",
        success: function(result) {
                callback(result);
        },
        error: function(xmlhr, status, err){
            console.error(err);
            var response = eval(err + ": ("+xmlhr.responseText+")");
            console.log(response);
		}
    });
}

