//this site won't be framed!
if (top.location != location) {
	top.location.href = document.location.href ;
}

//Global Variables
	var gaswebVersion = "b2.14.b130";														//second website 
	var loggingEnabled = false;																	//creates a container into which process status is injected
	var cacheEnabled = false;																		//must be enabled for site to work fast	(without could have script and css issues)
	
	//some preloading
	var images = ['./img/progress.gif', './css/prod/img/gasshutter.jpg','./prod/fiddler/img/fiddler_billing.png','./css/img/menu/slider-right.png']; //just add ."pic.ext'
	$(images).each(function(key, value) {
		var img = new Image();
		$(img).attr('src', value)
					.error(function (){
						alert('Error preloading image ' . value);
					})
	});
		
$(function(){

	//jQuery Scope Functions

	// bind global ajax event handlers
	$(document).ajaxStart(onStart)
	   .ajaxStop(onStop)
	   .ajaxSend(onSend)
	   .ajaxComplete(onComplete)
	   .ajaxSuccess(onSuccess)
	   .ajaxError(onError);

	   if ( loggingEnabled ) {
			$( "#body-wrapper" ).prepend( "<div id='log' style='padding:0 5px;border:1px dotted red;margin-left:1125px;position:absolute;'>LOG<br/></div>" );
		}

		$( "#floating-menu" ).makeFloat( {speed:"fast"});	
		$( '#floating-menu ul' ).lavaLamp( { fx: "easeOutBack" } );
		
		$( '#sitenav' ).lavaLamp( {
			fx: 'easeOutBack',
			speed: 1500,
			returnHome: true,
			homeLeft: 840,
			homeTop: 180,
			homeWidth:10,
			homeHeight:10
		} );

		//if user clicked on the link
		$( '#sitenav a' ).click(function () {  
		  page = $(this).attr('link');
		  if (page[0]=="#") return;		//do nothing 
		  loadPage( page );
	   });
		$( "#calendar" ).fullCalendar( {
			dayClick: function(date) {
				currentPage=$( "#body-wrapper" ).find("#open-plan");
				currentName=currentPage.attr( "name" );
				if (currentName !="events") {
					loadPage( 'events' );
				}
				//input = 'Sat Aug 14 2010 00:00:00 GMT+0200'
				//yy = date.substr(12,4);
				//dd = date.substr(9,2);
				//months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
				//mm = dayClicked.indexOf( date.substr(5,3) ); 
				window.setTimeout(function() {	
					$( "#diary" ).fullCalendar( 'gotoDate', date );
				},1000)
			}
		} );

		//menu navigation
		$( '#floating-menu a' ).click( function(){
			menuItem=$( '#floating-menu a' ).index( this );
			targetName=pageHive[menuItem];
			loadPage( targetName );
		}); //menu navigation end

		$("#weatherwidget").ready(function() {
			$("img","#wf_icon")
				.css("height","35px")
				.css("width","35px");
		});
		//debugging click function
		$("#gaslogo").click( function() {
				
		});
		//browser fixes
		window.setTimeout(function() {
			if ($.browser.msie) { 
				$('.round').corner( "10px" );
				$("#calendar").addClass("transparent");
			}
		},5000 );

		//Prepares siteCache - background cache all web pages - still buggy 30/6/2011
		$( "#siteCache" ).empty();                                                              		//refresh site cache upon request
		var pageHive=["home","productions","newsletter","membership","contacts","about","downloads","links","events"];
		if ( cacheEnabled ){
			createCache( pageHive );
		}
		loadFromServer( pageHive[0] );

}); //jQuery ready ( end )

//Global functions

//simple character shift encryption for decoding encrypted email addresses in the html body
function encr(U,X,R){
	for(i=0;i<U.length;++i)	{
		R+=String.fromCharCode(X^U.charCodeAt(i));
	}
	return R;
}

function log( html ) {
	if ( loggingEnabled ) {
		$( "#log" ).append( html );
	}
}

function pageLoaded( page ){
	currentPage=$( "#body-wrapper" ).find("#open-plan");
	currentName=currentPage.attr( "name" );
	return (currentName==page);
}

loadFromCache = function( page ){
	containers = "#main-content ,#side-bar";
	currentPage=$( "#body-wrapper" ).find("#open-plan");
    cachedPage="#"+page+"-cache"; 
		if ( $(cachedPage).length > 0 ) { 
			currentPage.replaceWith( "<div id='open-plan' name='"+page+"'></div>" ); //this is still buggy 20/7
																														log( "<br/>loading ["+page+"] from cache" );
			$( containers, cachedPage ).clone(true).appendTo( "#open-plan", "#body-wrapper" );
																														log( "<br/>apparently without errors" );
		}
	 return pageLoaded( page );
}

loadFromServer1 = function( page ) {
																													log( "<br/>loading ["+page+"] from server" );
	containers = "#main-content ,#side-bar";
	currentPage=$( "#body-wrapper" ).find("#open-plan");
	currentPage.attr( "name", "notLoaded" )
		.load( page+".htm " + containers )
		.attr( "name", page );
	return pageLoaded( page );
}

function loadFromServer( page ) {
																													log( "<br/>loading ["+page+"] from server *************" );
	currentPage=$( "#body-wrapper" ).find("#open-plan");
	$(currentPage).contents().empty();
	$.ajax( {
		dataType: "html",
		url: page + ".htm",
		cache: false,
		success: function( html ) {
			currentPage.replaceWith( "<div id='open-plan' name='"+page+"'></div>" );
			$( "#open-plan","#body-wrapper" ).html( html ); 				//append does not remove the container's text! [use .html()]
		}
	} );
	return pageLoaded( page );
}

function createCache( pageList ) {
	$.each( pageList, function( i,page ) {
		$.ajax( {
			url: page+".htm",
			cache: false,
			success: function( html ){
				$( "#siteCache" ).append( "<div id='"+page+"-cache'></div>" );							//inject empty container into cache
				//$("<head>").append( $("<script>", page) );
				$( "#"+page+"-cache" ).append( html );
																													log( "<br/>injected ["+page+"] into cache" );
				if ( (i+1)==pageList.length ) {
					loadFromCache( "home" ) ;
				}
			}
		} )
	} )
}

//is page loaded - yes do nothing and return
//is page cached - yes load from cache and return
//load from server

//loadPage function still buggy 30/6/11
function loadPage( targetName ) {
	window.location.href = "#top";
	er = "<br/> ["+targetName+"] not found ";
	try {
		if ( pageLoaded( targetName ) ) { 											throw er +"in focus - trying cache..."	}
		else if ( cacheEnabled && loadFromCache( targetName ) ) { 	throw er + "in cache - trying server..." 	}
		else  if ( loadFromServer( targetName ) ) {								throw er + "on server - oops..."	}
	}
	catch ( er ) {
		log (er);
	}
	finally {
		//fix IE border-radius rendering
		if ( targetName=="productions" ) {
			$( ".construction, .hiddenBehindDoor").removeClass("round")
		}
		//re-apply browser fixes
		$('.round').corner( "10px" );
	}
	return true;
}

// declare Ajax callback functions (from http://www.malsup.com/jquery/ajax/)
function onStart(event) {	
	//$("body").fadeTo("fast", 0.70);
	$("#progress").show();
	return;
	//$("#open-plan").append("<div id='progress'><img src='./img/progress.gif' /></div>");
	//$("#progress").animate( { marginLeft:"680px" }, { queue:false, duration:12000 } ).fadeOut(10000);
}
function onStop(event) {
	//$("body").fadeTo("fast", 1.0);
	$("#progress").hide();
}
function onSend(event, xhr, settings) {
	$("#progress").show();
	log("<br/> trying page: " + settings.url )
}
function onComplete(event, xhr, settings) {
    log("<br/> loaded page: " + settings.url );
	$("#progress").remove();
}
function onSuccess(event, xhr, settings) {
    log("<br/> done trying page: " + settings.url );
}
function onError(event, xhr, settings, err) {
	currentPage=$( "#open-plan #main-content","#body-wrapper" );
	currentPage.prepend( "<div class='heading round' style='color:red'>SYSTEM ERROR LOADING PAGE</div>" +
	"<div class='review round'>"  +
		"<h2 style='color:red'>Oh no, an error has occured! </h2>" +
		"<img src='img/home/errorpc.gif' style='float:right'/><h3>" +
		"The requested page could not be retrieved!<br/>" +
		"Retry by refreshing the home page ( F5 )<br/>" +
		"If this error persists, please contact the website designer.</h3>["+settings.url+"]" +
	"</div>" );
}
// create function to log the event info
function logEvent(event, xhr, settings, err) {
    var out = 'event: ' + event.type;
    // don't access the xhr's 'status' property too soon (some browsers will generate errors)
    if (xhr && xhr.readyState > 1)
        out += ';  statusCode: ' + xhr.status;
    // access settings object
    if (settings)
        out += ';  url: ' + settings.url;
    // log error message if there is one
    if (err)
        out += ';  error: ' + err;
    // add new div to log element
    $('#log').append( out );
}

