// Global Variables
var counterIncrement = 0,
testHeight;

function flashWrite(flashfile,x,y,flashvar) {
	document.write("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='"+ x +"' height='"+ y +"'>");
	document.write("<param name='movie' value='"+ flashfile +"' />");
	document.write("<param name='quality' value='high' />");
	document.write("<param name='flashvars' value='"+ flashvar +"' />");
	document.write("<param name='wmode' value='transparent' />");
	document.write("<embed src='"+ flashfile +"' wmode='transparent' ");
	document.write("flashvars='"+ flashvar +"'  ");
	document.write("quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='"+ x +"' height='"+ y +"'></embed>");
	document.write("</object>");
}

function printYear() {
	var today = new Date();
	document.write(today.getFullYear());
}

function writeEmail(email) {
	document.write('<a href="mailto:'+email+'">'+email+'</a>');
}

function changeTextSize(textSize) {
	document.body.className = 'site ' + textSize;
	return false;
}

function printPage() {
	window.print();
	return false;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function shortenBreadcrumb(options){
    /*  
        Shortens the breadcrumb to a specified width by removing the text from one list item
        at a time and replacing it with "..." - accepts an options object as an optional
        parameter with two options:
            shortenBreadcrumb({
                breadcrumb : $('div#breadcrumb > ul'),
                maxWidth : 725
            });
            
        The first is the selector for the breadcrumb ul, the second is the maximum width you
        want it to be.  If not set, the max width is the width of the container minus the width
        of the paragraph next to it ("You are here:").
            -JM
    */

    var breadcrumb = $('div#breadcrumb > ul');
    var maxWidth = parseInt($('div#breadcrumb').innerWidth()) - parseInt($('div#breadcrumb p').outerWidth(true)) + "px";
    
    if (options != undefined){
        if (options.breadcrumb != null) { breadcrumb = options.breadcrumb; }
        if (options.maxWidth != null) { maxWidth = options.maxWidth; }
    }
    
    var levelCount = breadcrumb.find('li').size();
    var shortEnough = false;
    var totalWidth;
    while (shortEnough == false) {
        totalWidth = 0;
        breadcrumb.children('li').each (function(){
            totalWidth += $(this).outerWidth(true);
        });
        if (totalWidth > maxWidth){
            var li = breadcrumb.children('li').not('.short').eq(1);
            li.addClass('short');
            li.children('a').attr('title', li.children('a').html());            
            li.children('a').html('...');
        }
        else {
            shortEnough = true;
        }
    }
}

function navigateURL(u) {
	var found = false;
    $('a.lnkAjaxRoot').each(function() {
        var th = $(this).attr('href');
        if (th === u) {
            found = true;
            $(this).click();
        }
    });
    if (!found) {
    	$('#vNav ul.subnav a').each(function (i, e) {
    		var $e = $(e), th = $e.attr('href');
    		if (u.indexOf(th) != -1) {
    			found = true;

    			var linkID = $e.attr('rel'),
				root = $e.parents('li.root').children('a'),
				rootID = root.attr('rel');

    			if (!$(rootID).hasClass('contentActive')) root.click();

    			$(rootID).find('div.contentMenu ul.subnav a').each(function (i, e) {
    				var th = $(e).attr('href');
    				if (u.indexOf(th) != -1) $(e).click();
    			});
    		}
    	});
    }
}

function checkTime(i) {
    if (i < 10) i = "0" + i;
    return i;
}
var t;
function startTime() {
    var today = new Date();
    // Date
    var d = today.getDay();
    var date = today.getDate();
    var month = today.getMonth();
    month = month + 1;
    var y = today.getFullYear();
    var day = new Array();
    day[0] = "Sun";
    day[1] = "Mon";
    day[2] = "Tue";
    day[3] = "Wed";
    day[4] = "Thu";
    day[5] = "Fri";
    day[6] = "Sat";
    // Time
    var h = today.getHours();
    var hsuffix = "AM";
    if (h > 12) { h = h - 12; hsuffix = "PM"; }
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    // 
    var time = day[d] + " " + date + "/" + month + "/" + y + " " + h + ":" + m + hsuffix;
    $('.clock').text(time);
    t = setTimeout('startTime()', 30000);
}

$(window).resize(function() {
    $('#middleWrap').css({ width: '100%' });
    var dw = $('#middleWrap').width();
    $('.contentWrap').width(dw);
    $('#middleWrap').width(dw);
    $('.contentWrap').css({ 'left': (dw) });
    $('.contentActive').css({ 'left': 0 });
});

$(window).load(function() {
    /*  */
    $('.contentWrap').css({ 'height': 'auto' });
    var dw = $('#middleWrap').width();
    $('.contentWrap').width(dw);
    $('#middleWrap').width(dw);
    $('.contentWrap').css({ 'left': (dw), 'position': 'absolute' });
    $('#middleWrap > div.contentWrap').first().css({ left: 0 });
    $('#middleWrap > div.contentWrap div.contentInner').first().css({ left: 0 }).addClass('subActive');
    var size = $('#vNav li a.linkActive').size();
    if (size < 1) {
        $('#logo a').addClass('linkActive');
    }    
    var h = 0;
    $('.contentWrap').each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);
    $('#middleWrap').height(h);
    /*  */

    $('.loading').fadeOut('fast');
});

function setupCarousel() {
    $('.carouselMask ul.feedListing').each(function(i, e) {
        if (!$(this).hasClass('aCarousel')) {
            $(this).adidoCarousel({
                autoStart: false,
                buttonNext: function(e) {
                    var parent = $(e).parents('.carouselMask');
                    var btn = parent.find('.btnCarouselNext');
                    return btn;
                },
                buttonPrev: function(e) {
                    var parent = $(e).parents('.carouselMask');
                    var btn = parent.find('.btnCarouselPrev');
                    return btn;
                },
                pager: true,
                pagerElement: function(e) {
                    var parent = $(e).parents('.carouselMask');
                    var pager = parent.children('.carouselPager');
                    return pager;
                },
                pagerStyle: 'numeric'
            });
        }
    });
}
function setupFlash() {
    $('#middleWrap').find('.flashItem').each(function(i, e) {
        if (!$(e).hasClass('flashActive')) {
            // Grab attributes
            var h = $(e).attr('height'),
            w = $(e).attr('width'),
            src = $(e).attr('rel'),
            id = $(e).attr('id');

            // Setup flash
            var flashvars = {};
            var params = {};
            params.wmode = "transparent";
            var attributes = {};
            attributes.id = id;
            swfobject.embedSWF(src, id, w, h, "9.0.0", false, flashvars, params, attributes);
            $(e).addClass('flashActive');
        }

    });
}

var Search_ = {};
var CallBack_ = {};
function setupGMap() {
    var gMaps = $('.googleMap').not('.gmapRendered');
    gMaps.each(function(i, e) {
        var $e = $(e), mapID = $e.attr('id'), mapPostcode = $e.attr('title');
        Search_.mapID = new GlocalSearch();
        Search_.mapID.setSearchCompleteCallback(null, CallBack_.mapID);

        Search_.mapID.execute(mapPostcode + ', UK');

        CallBack_.mapID = function() {
            var s = Search_.mapID;
            if (s.results[0]) {
                var resultLat = s.results[0].lat;
                var resultLng = s.results[0].lng;
                var point = new GLatLng(resultLat, resultLng);

                var map = new GMap2(document.getElementById(mapID));
                map.setCenter(point, 15);
                map.addControl(new GSmallMapControl());
                map.addOverlay(new GMarker(point));
                $e.addClass('gmapRendered');
            } else {
                alert("Postcode Not Found!");
            }
        }
    });
}

function ajaxRootLoad(r) {
    return true;
    $('a.lnkSeeOurTeam').unbind().click(function(e) {
        e.preventDefault();
        $('#vNav a.i2').click();
    });
}
function ajaxSubLoad(s) {
    // alert(s);

    $('.carouselMask ul.feedListing').each(function(i, e) {
        if (!$(this).hasClass('aCarousel')) {
            $(this).adidoCarousel({
                autoStart: false,
                buttonNext: function(e) {
                    var parent = $(e).parents('.carouselMask');
                    var btn = parent.find('.btnCarouselNext');
                    return btn;
                },
                buttonPrev: function(e) {
                    var parent = $(e).parents('.carouselMask');
                    var btn = parent.find('.btnCarouselPrev');
                    return btn;
                },
                pager: true,
                pagerElement: function(e) {
                    var parent = $(e).parents('.carouselMask');
                    var pager = parent.children('.carouselPager');
                    return pager;
                },
                pagerStyle: 'numeric'
            });
        }
    });
    
    return true;
}

$(document).ready(function () {

	var setupTimer = setInterval(function () {
		setupCarousel();
		setupFlash();
		setupGMap();

		$('div.contentFrame').each(function (i, e) {
			var $frame = $(e), h = 0;
			$('.contentInner', $frame).each(function (i, e) {
				var $e = $(e), th = $e.height();
				if (th > h) { h = th; }
			});
			$('.inner', $frame).height(h);
		});

		var newHeight = 730;
		$('#middleWrap > div').each(function (i, e) {
			var $e = $(e)
			$e.css({ 'height': 'auto' });
			var h = $e.height();
			if (h > newHeight) { newHeight = h; }
		}).parent().height(newHeight);
		newHeight = newHeight + $('#headerWrap').height();
		$('#wrap').css('min-height', newHeight);
	}, 500);

	$('body').removeClass('noJS');
	$('#jsWarning').hide();

	$('div.textBlock li').each(function (i, e) {
		var p = $(e).find('p');
		var h = $(e).height();
		var fs = p.css('font-size');
		fs = parseInt(fs);
		fs = Math.floor(fs);
		if (h > 308) {
			while (h > 308) {
				fs = fs - 5;
				p.css('font-size', fs);
				h = $(e).height();
			}
		}
	});

	$('div#vNav > ul > li').addClass('root');

	startTime();

	if ($('div.lightbox').length > 0) {
		$('div.lightbox a').lightBox({
			imageLoading: '/system/assets/images/lightbox/lightbox-ico-loading.gif',
			imageBtnClose: '/system/assets/images/lightbox/lightbox-btn-close.gif',
			imageBtnPrev: '/system/assets/images/lightbox/lightbox-btn-prev.gif',
			imageBtnNext: '/system/assets/images/lightbox/lightbox-btn-next.gif'
		});
	}



	$('.searchBox input.textBox').focus(function () {
		var t = $(this).attr('rel');
		var v = $(this).val();
		if (v == t) {
			$(this).val('');
		}
	}).blur(function () {
		var t = $(this).attr('rel');
		var v = $(this).val();
		if (v == '') {
			$(this).val(t);
		}
	});

	$('input.textClear').each(function () {
		var v = $(this).val();
		$(this).attr('title', v);
	});
	$('input.textClear').focus(function () {
		var t = $(this).attr('title');
		var v = $(this).val();
		if (v == t) {
			$(this).val('');
		}
	}).blur(function () {
		var t = $(this).attr('title');
		var v = $(this).val();
		if (v == '') {
			$(this).val(t);
		}
	});

	/*  */

	var flashid = "homeFlash" + counterIncrement;
	$('div#homeFlash').attr('id', flashid);
	counterIncrement = counterIncrement + 1;
	var flashvars = {};
	var params = {};
	params.wmode = "transparent";
	var attributes = {};
	attributes.id = flashid;
	swfobject.embedSWF("/cms/site/flash/Clock_v2.swf", flashid, "700", "850", "9.0.0", false, flashvars, params, attributes);
	/*  */


	/* Start AJAX */

	/* Add classes to all root elements */
	$('#vNav > ul > li > a').addClass('lnkAjaxRoot');
	$('#vNav > ul > li.navdrop > a').addClass('lnkAjaxRootDrop');
	$('#logo a').addClass('lnkAjaxRoot');

	$('.testLink').live('click', function (e) {
		e.preventDefault();
		var h = $(this).attr('href');
		navigateURL(h);
	});

	/* Load root-level items */
	$('.lnkAjaxRoot').each(function (i, e) {
		var rootURL = $(e).attr('href');
		var contentWrap = $('<div class="contentWrap"></div>');
		var content = $('<div class="content"></div>');
		contentWrap.attr('id', 'i' + i);
		content.load(rootURL + ' #ajaxLoadContent', function (response, status, xhr) {
			if (status === "error") {
				content.html('<div class="pageError"><p>Error loading page</p></div>');
			}
			ajaxRootLoad(rootURL);
		}).appendTo(contentWrap);
		contentWrap.appendTo('#middleWrap');
		$(e).attr('rel', '#i' + i);
	}).click(function (e) {
		e.preventDefault();
		if (!$(this).hasClass('linkActive')) {
			var target = $(this).attr('rel');
			var width = $('#middleWrap').width();
			// Move current item off to the left
			$('.contentActive').animate({ left: -width }, function () {
				$(this).css({ left: (width * 2) });
			}).removeClass('contentActive');
			$(target).animate({ left: 0 }).addClass('contentActive');
			$('a.linkActive').removeClass('linkActive');
			$(this).addClass('linkActive');
		}
	});


	// Load sub pages when main page has sublinks
	$('div.contentActive').each(function (i, e) {
		var subWidth = 815;
		var rootID = $(this).attr('id');
		var subPane = $(this);
		var subPaneMenu = $(this).find('div.contentMenu')
		var subPaneInner = $(this).find('div.inner');
		subPaneMenu.find('a').each(function (i, e) {
			if ($(this).parent().hasClass('navdrop')) {
				$(this).addClass('lnkAjaxSubDrop');
			} else {
				var itemID = rootID + "_s" + i;
				var subURL = $(this).attr('href');
				var innerContent = $('<div class="contentInner"></div>');
				$(this).attr('rel', "#" + itemID);
				innerContent.attr('id', itemID).load(subURL + ' #ajaxLoadContent', function () { ajaxSubLoad(itemID) }).appendTo(subPaneInner);
			}
		}).click(function (e) {
			e.preventDefault();
			if ($(this).hasClass('lnkAjaxSubDrop')) {
				$(this).next('ul.subnav').slideToggle();
				$(this).parent().toggleClass('active');
			} else {
				if (!$(this).hasClass('lnkAjaxSubActive')) {
					var subTarget = $(this).attr('rel');
					$('.subActive').stop().animate({ left: -subWidth }, function () { $(this).css({ left: subWidth }); }).removeClass('subActive');
					$(subTarget).stop().animate({ left: 0 }).addClass('subActive');
					$('.lnkAjaxSubActive').removeClass('lnkAjaxSubActive');
					$(this).addClass('lnkAjaxSubActive');
				}
			}
		});
	});

	// Load sub pages when parent link is clicked
	$('a.lnkAjaxRootDrop').click(function (e) {
		var subWidth = 815;
		e.preventDefault();
		if (!$(this).hasClass('ajaxLoaded')) {
			var rootID = $(this).attr('rel');
			var subPane = $(rootID);
			rootID = rootID.replace(/#/, "");
			var subPaneMenu = subPane.find('div.contentMenu');
			var subPaneInner = subPane.find('div.inner');
			subPaneMenu.find('a').each(function (i, e) {
				if ($(this).parent().hasClass('navdrop')) {
					$(this).addClass('lnkAjaxSubDrop');
				} else {
					var itemID = rootID + "_s" + i;
					var subURL = $(this).attr('href');
					var innerContent = $('<div class="contentInner"></div>');
					$(this).attr('rel', "#" + itemID);
					innerContent.attr('id', itemID).load(subURL + ' #ajaxLoadContent', function () { ajaxSubLoad(itemID); }).appendTo(subPaneInner);
				}
			}).click(function (e) {
				e.preventDefault();
				if ($(this).hasClass('lnkAjaxSubDrop')) {
					$(this).next('ul.subnav').slideToggle();
					$(this).parent().toggleClass('active').siblings('.active').removeClass('active').children('ul.subnav').slideUp();
				} else {
					var subTarget = $(this).attr('rel');
					$('.subActive').stop().animate({ left: -subWidth }, function () { $(this).css({ left: subWidth }); }).removeClass('subActive');
					$(subTarget).stop().animate({ left: 0 }).addClass('subActive');
				}
			});
			$(this).addClass('ajaxLoaded');
		}
		var target = $(this).attr('rel');
		$(target).find('.contentInner').first().addClass('subActive').animate({ left: 0 }).addClass('subActive').siblings('.subActive').animate({ left: -subWidth }, function () { $(this).css({ left: subWidth }); }).removeClass('subActive');
	});

	$('#vNav > ul > li > a').each(function (i, e) {
		// Class set for menu sprite position
		$(e).addClass('i' + i);
	});

	/* End AJAX */

	$(':first-child').addClass('first');
	$(':last-child').addClass('last');
	$('a[rel=newWindow]').attr('target', '_blank');

	// $('.loading').fadeOut('fast');
});
