﻿/*
* Kajima IntranetxJavascript
* --------------------------
* J Barr
* --------------------------
* Core Lib
* rev 0.98.1
* 03.01.2011 
* --------------------------
*/

$(document).ready(function() {

    initQuickSearch();
    initFooter();
    
    $(".selectbox").selectbox();
    
    if ($(".fLogin").length) { initLogin(); }
    if ($(".fProfile").length) { initProfile(); }
    
    if ($(".rotating_images").length) { initRotatingImages(); }
    if ($("#sidebarmenu1").length) { initsidebarmenu(); }
   
    $(".datepicker").datepicker({dateFormat: 'dd/mm/yy'});
    
	$(".galleryOpener").prettyPhoto({ theme:'light_rounded' });
	
	if($("#calendar").length) { initCalendar(); }
});

function initCalendar() {

    $("#txtEventDate").datepicker({dateFormat: 'dd/mm/yy'});
    $(".fEventinator").submit(function() { return false; });
    
    clearEvent();
    
    var calendar = $("#calendar").fullCalendar({
      theme: true,
      header: {
				left: 'prev,next today',
				center: 'title',
				right: 'agendaDay,agendaWeek,month' //,month <-disallow
	  },
	  events: {
	     url: "/event.connector.ashx?room=" + $("#hdnRoomID").val(),
	     ignoreTimezone: false
	  },
      defaultView: 'agendaWeek',
      allDaySlot: false,
      firstDay: 1,
      minTime: 7,
      slotMinutes: 30,
      ignoreTimezone: false,
      defaultEventMinutes: 60,
      columnFormat: { month: 'ddd', week: 'ddd d/M', day: 'dddd d/M' },
      axisFormat: 'HH:mm',
      timeFormat: 'HH:mm',
      firstHour: 7,
      editable: true,
      selectable: true,
      selectHelper: true,
      select: function(start, end, allDay) {
      
          // if allDay then its in month view : change to day view
          if(allDay == true) {
              $("#calendar").fullCalendar('gotoDate', start).fullCalendar('changeView', 'agendaWeek');
              //$("#calendar").fullCalendar('changeView', 'agendaWeek');
          } else {
              eventinate(start, end, allDay, function(res) {
                   
              });
          }
      
//      var title = prompt('Event Title:');
//		if (title) {
//		    calendar.fullCalendar('renderEvent',
//			{
//				title: title,
//				start: start,
//				//				end: end, 
//                allDay: allDay
//			},
//			true // make the event "stick"
//		    );
//		}
//		calendar.fullCalendar('unselect');
      },
//      eventMouseover: function(event, jsEvent, view) {
//        $("#eventTitle-title").html(event.title);
//        $("#eventTitle-date").html(event.dateFormatted);
//        $("#eventTitle-org").html(event.org);
//        $("#eventTitle-body").html(event.body);
//        
//        $("#eventTitle").css("top", jsEvent.clientY + 130);
//        $("#eventTitle").css("left", jsEvent.clientX + 10);
//        $("#eventTitle").show();
//      },
//      eventMouseout: function(event, jsEvent, view) {
//        $("#eventTitle").hide();
//      },

        // on move
      eventDrop: function(ev, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
      
        if (!confirm("Are you sure you want to move this appointment?")) {
            revertFunc();
        } else {
        
            moveEvent(ev, function(res) {
                if (res.success !== true) {
                    alert(res.error);
                    revertFunc();
                }
            });
        }
      },
      eventResize: function( ev, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) { 
        if (!confirm("Are you sure you want to change this appointment?")) {
            revertFunc();
        } else {
        
            moveEvent(ev, function(res) {
                if (res.success !== true) {
                    alert(res.error);
                    revertFunc();
                }
            });
        }
      },
      eventClick: function(ev, jsEvent, view) {
        
        if (ev.editable) {
            editMeeting(ev, function() {
        
        });
     } else { 
        alert("Not editable");
     }
      }
    });
    
    setTimeout("reloadEvents();", 10000);
}

function moveEvent(ev, callback) {

    start = Math.round((new Date(ev.start)).getTime() / 1000);
    end = Math.round((new Date(ev.end)).getTime() / 1000);
    
    data = {
        qry: "moveEvent",
        meetingID: ev.meetingID,
        start: start,
        end: end
    };
    ajaxRequest(data, "/x.connector.ashx", function(res) {
        callback(res);
    });
}

function eventinate(start, end, allDay, callback){
    //alert(start.getDate() + " ");
    //alert(start.getDay() + "/" + (start.getMonth()+1) + "/" + start.getFullYear());
    
    //alert(start);
    //var date = start.getDate() + "/" + (start.getMonth()+1) + "/" + start.getFullYear();
    
    // init fields
    //$("#spnCurrentDate").html(date);
    //$("#hdnEventDate").val(date);
    //$("#ddlStartHour").val(start.getHours());
    //$("#ddlStartMinute").val(start.getMinutes());
    //$("#ddlEndHour").val(end.getHours());
    //$("#ddlEndMinute").val(end.getMinutes());
    
    start = Math.round((new Date(start)).getTime() / 1000);
    end = Math.round((new Date(end)).getTime() / 1000);
    
    data = {
        qry: "loadRoomBooker",
        nodeID: $("#hdnNodeID").val(),
        sectionID: $("#hdnSectionID").val(),
        room: $("#hdnRoomID").val(),
        start: start,
        end: end
    };
    
    ajaxRequest(data, "/x.connector.ashx", function(res) {
        if (res.success == true) {
            $("#roombooker").html(res.html);
	        $("#eventinator").fadeIn("200");
	        $("#eventinator").parent().children(".overlay").fadeIn("200");
	    } else {
	        alert(res.error);
	    }
    });

    callback();
}

function editMeeting(ev, callback) {

    start = Math.round((new Date(ev.start)).getTime() / 1000);
    end = Math.round((new Date(ev.end)).getTime() / 1000);
    
    data = {
        qry: "loadRoomBooker",
        nodeID: $("#hdnNodeID").val(),
        meetingID: ev.meetingID,
        sectionID: $("#hdnSectionID").val(),
        room: $("#hdnRoomID").val(),
        start: start,
        end: end
    };
    
    ajaxRequest(data, "/x.connector.ashx", function(res) {
        
        if (res.success == true) {
	        $('html, body').animate({scrollTop:0}, 'fast');
            $("#roombooker").html(res.html);
	        $("#eventinator").fadeIn("200");
	        $("#eventinator").parent().children(".overlay").fadeIn("200");
	    } else {
	        alert(res.error);
	    }
    });

    callback();
}

function deleteMeeting(meetingID) {

   if (confirm("Are you sure you want to cancel this meeting?") == false) {
    return false;
   }
   
   data = {
        qry: "deleteEvent",
        meetingID: meetingID
   }
        
   ajaxRequest(data, "/x.connector.ashx", function(res) {
        
        if (res.success == true) {
        
            $("#eventinator").parent().children(".overlay").fadeOut("200", function() {
                $("#roombooker").html(res.html);
                $("#eventinator").fadeOut("200");
            });
        } else {
            alert(res.error);
        }

        $("#calendar").fullCalendar("refetchEvents");
   });
}

function submitEventinate() {
    
    var errors = "";
    
    if ($("#txtSubject").val().length <= 0) {
        errors = errors + "- Please enter the subject\n";
    }
    
    if ($("#ddlDepartment").val().length <= 0) {
        errors = errors + "- Please select your department\n";
    }
    
    if (errors.length > 0) {
        alert(errors);
        return false;
    }
    
    $("#btnEventSubmit").attr("disabled", "true");
    
    var drinks = [];
    $.each($(".fEventinator input[name='Drinks']:checked"), function() {
        drinks.push($(this).val()); 
    })
    var food = [];
    $.each($(".fEventinator input[name='Food']:checked"), function() {
        food.push($(this).val()); 
    })
    
    data = {
        qry: "saveEvent",
        MeetingID: $("#hdnMeetingID").val(),
        RoomID: $("#hdnRoomID").val(),
        EventDate: $("#hdnEventDate").val(),
        StartHour: $("#ddlStartHour").val(),
        StartMinute: $("#ddlStartMinute").val(),
        EndHour: $("#ddlEndHour").val(),
        EndMinute: $("#ddlEndMinute").val(),
        Subject: $("#txtSubject").val(),
        Department: $("#ddlDepartment").val(),
        Drinks: drinks,
        Food: food,
        MeetMe: $("#chkMeetMe").is(':checked'),
        Requirements: $("#txtRequirements").val(),
        Attendees: $("#txtAttendees").val(),
        External: $("#txtExternal").val()
    };
    
    ajaxRequest(data, "/x.connector.ashx", function(res) {
    
        if (res.success == true) {
            
	        $("#eventinator").parent().children(".overlay").fadeOut("200", function() {
	            $("#eventinator").fadeOut("200", function() {
	                $("#calendar").fullCalendar('refetchEvents');
	            });
	        });
	
	        
	        // remove if already exists!
            $("#calendar").fullCalendar("removeEvents", res.obj.id);
            
            $("#calendar").fullCalendar("renderEvent", res.obj);
            
            $("#roombooker").html("");
            clearEvent();
            
        } else {
            alert(res.error);
        }
    
        $("#btnEventSubmit").removeAttr("disabled");
    });
    
    return false;
}

function reloadEvents() {
    $("#calendar").fullCalendar('refetchEvents');
    
    setTimeout("reloadEvents();", 8000);
}

function checkAvailability() {

    data = {
        qry: "checkAvailability",
        RoomAccount: $("#"+roomID).val(),
        EventDate: $("#" +txtEventDate).val(),
        StartHour: $("#"+ddlStartHour).val(),
        StartMinute: $("#"+ddlStartMinute).val(),
        EndHour: $("#"+ddlEndHour).val(),
        EndMinute: $("#"+ddlEndMinute).val(),
        MeetingID: $("#"+hdnMeetingID).val()
    };
    
    ajaxRequest(data, "/x.connector.ashx", function(res) {
    
        if (res.success == true) {
            alert("Room is available");
        } else {
            alert("Room is not available");
        }
   });
    
   return false;
}

function cancelEventinate() {

    clearEvent();
    
	$('html, body').animate({scrollTop:0}, 'fast');
			
    $("#eventinator").parent().children(".overlay").fadeOut("200", function() {
        $("#eventinator").fadeOut("200", function () {
            $("#roombooker").html(""); 
        });
	});
   return false;
}

function clearEvent() {

//    $("#btnEventSubmit").removeAttr("disabled");
//    $("#txtEventDate").val("");
//    $("#ddlStartHour").val("0");
//    $("#ddlStartMinute").val("0");
//    $("#ddlEndHour").val("0");
//    $("#ddlEndMinute").val("0");
//    $("#ddlDepartment").val("");
//    $("#txtSubject").val("");
//    $("#txtExternal").val("");
//    $("#txtDescription").val("");
//    $("#txtAttendee").val("");
//    $("#txtSubject").val("");
//    
//    $.each($(".fEventinator input[name='Drinks']"), function() {
//        $(this).removeAttr("checked");
//    })
//    var food = [];
//    $.each($(".fEventinator input[name='Food']"), function() {
//        $(this).removeAttr("checked");
//    })
}

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
        }
    }); 
}


// Profile Form
function initProfile() {
    $(".fProfile").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 },
            Office: { required: true },
            Timezone: { required: true }
        },
        messages: {
            FirstName: valProfile_Required_FirstName,
            LastName:  valProfile_Required_LastName,
            Email: { required: valProfile_Required_Email, email: valProfile_Invalid_Email },
            //Telephone: valProfile_Required_Telephone,
            Office: valProfile_Required_Office,
            Timezone: valProfile_Required_Timezone
        }
    }); 
}

// 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,
        async: false,
        data: data,
        dataType: "json",
        success: function(result) {
                callback(result);
        },
        error: function(xmlhr, status, err){
		}
    });
}

