var moveToFirst = true;
var IsCMSEnabled = false;

var pages = [
	{
		id 	: 'home',
		cId	: 'page1',
		url	: null,
		title: document.title,
		isLoading	: false,
		loaded	 	: true,
		cache		: null,
		getSubPagesFromServer   : false
	},{
		id 	: 'our-company',
		cId	: 'page2',
		url	: 'our-company.htm',
		title: 'Medina Dairy | Our Company',
		isLoading	: false,
		loaded	 	: true,
		cache		: null,
		getSubPagesFromServer   : false,
		subPages	: {
			'family-beginnings'	: ['Family Beginnings','our-company/family-beginnings.htm'],
			'our-vision' 		: ['Our Vision','our-company/our-vision.htm'],
			'current-clients' 	: ['Current Clients', 'our-company/current-clients.htm'],
			'environment' 		: ['Environment','our-company/environment.htm'],
			'csr' 				: ['','our-company/csr.htm']/*,
			'careers' 			: 'our-company/careers.htm'*/
		}
	},{
		id 	: 'our-brands',
		cId	: 'page3',
		url	: 'our-brands.htm',
		title: 'Medina Dairy | Our Brands',
		isLoading	: false,
		loaded 		: true,
		cache		: null,
		getSubPagesFromServer   : false,
		subPages	: {
		    'watsons': ['Watsons', 'our-brands/watsons.htm'],
		    'wealsosupply': ['WeAlsoSupply', 'our-brands/wealsosupply.htm']
		}
	},{
		id 	: 'our-products',
		cId	: 'page4',
		url	: 'ourproducts.aspx',
		title: 'Medina Dairy | Our Products',
		isLoading	: false,
		loaded 		: true,
		cache		: null,
		getSubPagesFromServer   : true
	},{
		id 	: 'food-service',
		cId	: 'page5',
		/*url	: 'food-service.htm',*/
		url	: 'foodservice.aspx',
		title: 'Medina Dairy | Food Service',
		isLoading	: false,
		loaded	 	: true,
		cache		: null,
		getSubPagesFromServer   : true
	},{
		id 	: 'media-centre',
		cId	: 'page6',
		url	: 'media-centre.htm',
		title: 'Medina Dairy | Media Centre',
		isLoading	: false,
		loaded 		: true,
		cache		: null,
		getSubPagesFromServer   : false,
		subPages	: {
			'in-the-press' : ['In the Press','media-centre/in-the-press.htm']
		}
	},{
        id: 'contact-us',
        cId: 'page7',
        url: 'contact-us.htm',
        title: 'Medina Dairy | Contact Us',
        isLoading: false,
        loaded: true,
        cache: null,
        getSubPagesFromServer: false
    },{
        id: 'farmer-recruitment',
        cId: 'page8',
        url: 'farmer-recruitment.htm',
        title: 'Medina Dairy | Farmer Recruitment',
        isLoading: false,
        loaded: true,
        cache: null,
        getSubPagesFromServer: false
    }
];

var currPage = '/';
var prevPage = '';
var isAnimatingScroll = false;
var regExMedinaUrl=new RegExp('/((\\w|\\w+-\\w+)+)/*((\\w|\\w+-\\w+)+)/$');

$(document).ready(function() {
    if ($.browser.msie && $.browser.version.split('.')[0] == '6') {
		//The user is using Internet Explorer 6, apply fix for footer
		$(window).scroll(function(){
			$('.mainFooter').css('left',$(window).scrollLeft()+'px');
		});
	}
	$('.mainFooter').css('width',Math.max(1000,$(window).width())+'px');
    $(window).resize(function() {
        $('.mainFooter').css('width',Math.max(1000,$(window).width())+'px');
    });

    //Set the setting for CMS
    if ($('#IsCMSEnabled').val() == 'true')
    {
        IsCMSEnabled = true;
    }
        
    
    //If our-products and food-service is loaded in a control then add dyanmic subpages from hidden field into the object.
    var sectionProducts = mapUrl('our-products');
    if (sectionProducts.loaded)
    {
        addDynamicSubpagesInObject(sectionProducts.id);
        saveInCache(sectionProducts.id);
    }
    
    var sectionFood = mapUrl('food-service');
    if (sectionFood.loaded)
    {
        addDynamicSubpagesInObject(sectionFood.id);
        saveInCache(sectionFood.id);
    }
        
        
	//Override all _internal_ links
	if ($.address.value() == '/' && currPage == '/') {
		changePage('home');
	}

    /* JRW:bind onclick event handler for all anchors - this binding will apply to anchors added retrospectively */	
	$('a:not(a[class~="menu-group-parent"])').live('click', function(){
	    var re=/http|ftp|mailto/i;
	    var re2=/medina/i;
	    var href;
	    if (!(href=$(this).attr('href')).match(re)||href.match(re2)){
    	    var section=href.match(regExMedinaUrl);
		    if (section&&mapUrl(section[0].split('/').removeEmpty()[0])!=null){
			    changePage(section[0]);
			    return false;
		    } else{
			    //Internal link, but not scrollable. For example: the legal section
		    }
	    }
	});
	
	// JRW:menu group handling
	$('a[class~="menu-group-parent"]').live('click',function(e){
	    e.preventDefault();
	});
	$('a[class~="menu-group-parent"]').live('mouseenter',function(){
	    var id=$(this).attr('href');
	    var mgitems=$('#'+id.slice(id.lastIndexOf('/')+1));
	    if (mgitems.attr('visited')!='true'){
	        mgitems.css('display','inline');
	        mgitems.mouseenter(function(){
	            var mgitems=$(this);
	            mgitems.attr('visiting',true);
	            $('a[href="'+mgitems.attr('id')+'"]').addClass('selected');
	        });
	        mgitems.mouseleave(function(){
	            var mgitems=$(this);
	            mgitems.attr('visiting',false);
	            mgitems.attr('visited',true);
	            setTimeout(function(){
	                if (mgitems.attr('visited')=='true'){
	                    mgitems.attr('visited',false);
	                    mgitems.css('display','none');
	                }
	            },250);
	            setTimeout(function(){
	                $('a[href="'+mgitems.attr('id')+'"]').removeClass('selected');
	            },250);
	        });
	    } else
	        mgitems.attr('visited',false); // cancel the visited status to permit closure
	});
	$('a[class~="menu-group-parent"]').live('mouseleave',function(){	
        var id=$(this).attr('href');
	    var mgitems=$('#'+id.slice(id.lastIndexOf('/')+1));
        setTimeout(function(){
    	    if (mgitems.attr('visiting')!='true')
	            mgitems.css('display','none');
    	});
	});
	
	loadPages();
	
	$.address.change(addressChanged);
	//setInterval("findClosestPage()", 500);
});


function changePage(newPage) {
    var parts = $.address.value().split('/').removeEmpty();
    if (parts.length == 1)
    {
        var currPageObj = mapUrl(currPage);
	    if (currPageObj.getSubPagesFromServer)
	        saveInCache(currPageObj.id);
	}
	
	$.address.value(newPage);
}

function addressChanged(event) { 
	var parts = event.value.split('/').removeEmpty();
    var section = parts[0];
    var subPage = '';
	var sectionObj = mapUrl(section);
	
	
	
	if (sectionObj.subPages != null) {
	    if (parts.length > 1)
	        subPage = parts[1];
	    
	    //If all the pages are already loaded then just show and hide panes
	    //otherwise loadSubpages from server using ajax or if its main page then load the page from cache.
	    if (!sectionObj.getSubPagesFromServer)
	    {
	        showSubPage(section, subPage);
	    }
	    else
	    {
	        if (subPage != '')
	            loadSubPage(section, subPage);
	        else
	        {
	            loadFromCache(section);
	            initCMS();
	        }
	    }
    }
    
    if (section != currPage)
    {
	    if (section == '/') {
		    section = 'home';
	    }
		
	    currPage = section;
		
	    if (prevPage == '') {
		    if (section != 'home') {
			    //alert(section);
			    $(window).scrollTo($('#' + mapUrl(section).cId), 0, {easing: null});
		    }
		    prevPage = section;
	    } 
		
	    var gotoPage = mapUrl(section);
	    document.title = gotoPage.title;
		
	    if (gotoPage != null) {
		    loadPage(gotoPage, scrollToPage);
	    } else if (moveToFirst) {
		    moveToFirst = false;
	    }
    }
    
}

function showSubPage(section, subPage) {
    var sectionObj = mapUrl(section);
    if (sectionObj != null) {
        if (sectionObj.subPages != null && sectionObj.subPages[subPage] != null) {
            hideAllSubpages(section);
            $('#' + section + '_' + subPage).show();
            
            document.title = sectionObj.title+' - '+sectionObj.subPages[subPage][0];
        }
        else {
            hideAllSubpages(section);
            $('#' + section).show();
            
            document.title=sectionObj.title;
        }
        
        highlightSelectedSubmenu(section,subPage);
        initCMS();
    }
}
function hideAllSubpages(section) {
    $('[id^=' +section+ ']').hide();
}
function hideAstrayEditButtons()
{
    $('.icms-icon-div').each(function() {
        if ($(this).css('top') == '2px')
            $(this).hide();
    });
}

function highlightSelectedSubmenu(section,subPage) {
    var sectionObj = mapUrl(section);
    var sectionPage = $('#' + sectionObj.cId);
    var subMenu = sectionPage.find("ul.subMenu");
    subMenu.find('a.selected').removeClass('selected');	
    
    var sel = subMenu.find('a[href$="' + section + '/' + subPage + '/"]');
    if (sel.length == 0) {
	    subMenu.find('a:first').addClass('selected');
    } else {
        if (sel.parents('.menu-group')[0])
            sel.parents('.menu-group').children('.menu-group-parent').addClass('selected');	
        sel.addClass('selected');
    }
}

function loadFromCache(sectionId)
{
    var sectionObj = mapUrl(sectionId);
    if (sectionObj.cache!=null)
        $('#'+sectionObj.cId).html(sectionObj.cache);
    document.title=sectionObj.title;
}
function saveInCache(sectionId)
{
    var sectionObj = mapUrl(sectionId);
    sectionObj.cache = $('#'+sectionObj.cId).html();
}

function loadSubPage(section, subPage) {
	//Find parent object:
	var sectionObj = mapUrl(section);
	if (sectionObj != null) {
		//Find subpage
		if (sectionObj.subPages != null && sectionObj.subPages[subPage] != null) {
			//Try to find ".mainContent-wrapper" div in current section 
			var sectionPage = $('#' + sectionObj.cId);
			var contentWrapper = sectionPage.find(".mainContent-wrapper");
			if (contentWrapper != null && contentWrapper != undefined) {
				$.get(sectionObj.subPages[subPage][1], function(data) {
				
					contentWrapper.html(data);
					document.title = sectionObj.title+' - '+sectionObj.subPages[subPage][0];
					
					highlightSelectedSubmenu(section,subPage);
					initCMS();
					
				});
			}
		}
		else
		{
		    /* JRW:to allow 'sub' navigation back to the main page */
		    if (sectionObj.cache!=null)
		        $('#'+sectionObj.cId).html(sectionObj.cache);
	        document.title=sectionObj.title;
		}
	}
}

function initCMS()
{
    if (IsCMSEnabled)
    {
        icmsRegenerateLayers();
        hideAstrayEditButtons()
    }
}
function mapUrl(id) {
	id = id.split('/').removeEmpty().join('/');
	for (var i = 0; i < pages.length; i++) {
		var currPage = pages[i];
		if (currPage.id == id) {
			return currPage;
		}
	}
	return null;
}

Array.prototype.removeEmpty = function() {
	var returnArray = [];
	for(var i=0; i < this.length; i++) {
		if (this[i] != null && this[i] != '') {
			returnArray.push(this[i]);
		}
	}
	return returnArray;
}

function scrollToPage(gotoPage) {
	isAnimatingScroll = true;
	var properties = {easing:'easeInOutCubic', onAfter:function() {isAnimatingScroll = false;}};
	var time = 1000;
	/*if (moveToFirst) {
		moveToFirst = false;
		properties.easing = null;
		time = 0;
	}*/
	var target = $('#' + gotoPage.cId);
	if (gotoPage.cId == 'page1') {
		target = $('body');
	}
	// animate scroll in FF on history navigate 
	//$(window).scrollTo($('#' + mapUrl(prevPage).cId), 0, {easing: null});
	
	// JRW:just to limit the impact of footer scroll position
	if ($.browser.msie && $.browser.version.split('.')[0] == '6'){
	    $('.mainFooterContact table').fadeTo(100,0.2,function(){
            setTimeout(function(){
                $('.mainFooterContact table').fadeTo(100,1);
                },800);
        });
    }
	
	prevPage = currPage;
	
	$(window).scrollTo(target, time, properties);
}

function loadPages() {
	//load pages asynchronously in the background
	for (var i = 0; i < pages.length; i++) {
		var pageObj = pages[i];
		if (!pageObj.loaded) {
			if (!pageObj.isLoading) {
				//loadPage(pageObj, loadPages);
				loadPage(pageObj, null);
			}
		}
	}
}

function loadPage(pageObj, callback) {
	if (!pageObj.loaded) {
		if (!pageObj.isLoading) {
			pageObj.isLoading = true;
			var cacheDiv = document.createElement('div');
			$.get(pageObj.url, function(data) {
				pageObj.isLoading = false;
				pageObj.loaded = true;
				pageObj.cache = data;
				$('#' + pageObj.cId).html(data);
				
				/* JRW:added to allow dynamic sub page content */
                addDynamicSubpagesInObject(pageObj.id);
                
				if (callback!=null)
	                callback(pageObj);
			});
		}
	} else {
		if (callback!=null)
	        callback(pageObj);
	}
}

function addDynamicSubpagesInObject(sectionId)
{
    var subpages;
    var sectionObj = mapUrl(sectionId);
    if ((subpages=$('#'+sectionObj.cId+' input[name="subpages"]'))[0])
        sectionObj.subPages=$.parseJSON(subpages.val());
}

var previousX = 0;
var wasMoving = false;

function findClosestPage() {
	var tmpX = $(window).scrollLeft();
	if (previousX != tmpX) {
		wasMoving = true;
	} else if (wasMoving) {
		wasMoving = false;
		document.title = "moved " + tmpX;
		
		//Find closest page
		for (var i = 0; i < pages.length; i++) {
			var pageObj = pages[i];
			if (Math.abs($('#' + pageObj.cId).position().left - tmpX) < 400) {
				scrollToPage(pageObj);
				break;
			}
		}
	}
	previousX = tmpX;
}


function selectMenuItem(sectionPage,section,subPage,anchor){
	var subMenu = sectionPage.find("ul.subMenu");
	//alert(subMenu.find('a'));
	subMenu.find('a').removeClass('selected');
	var sel = (anchor!=null?$(anchor):subMenu.find('a[href$="' + section + (subPage!=''?'/'+subPage+'/':'') + '"]')).addClass('selected');
	if (sel.length == 0){
		//Select first item
		subMenu.find('a:first').addClass('selected');
	}
}

function submitContactUs(){
    /* do some validation */
    var field,msg;
    var rWhitespace=/\s/g;
    var rEmail=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if ((field=$('#cfe-name')).val().replace(rWhitespace,'')=='')
        msg='Please enter your name.';
    else if ((field=$('#cfe-email')).val().replace(rWhitespace,'')==''||
            !rEmail.test(field.val()))
        msg='Please enter a valid email address.';
    else if ((field=$('#cfe-phone')).val().replace(rWhitespace,'')=='')
        msg='Please enter your telephone number.';
    else if ((field=$('#cfe-enquiry')).val().replace(rWhitespace,'')=='')
        msg='Please enter your enquiry.';
    if (msg){
        alert(msg);
        field.focus();
    } else {
        $.ajax({
            type:"POST",
            url:'/contactus.ashx',
            dataType:'json',
            data:{
                name:$('#cfe-name').val(),
                email:$('#cfe-email').val(),
                phone:$('#cfe-phone').val(),
                enquiry:$('#cfe-enquiry').val()},
            success:function(data){
                if (data.error)
                    alert(data.error);
                else{/* show acknowledge */
                    saveInCache('contact-us');
                    $('.mainContent-left table').remove();
                    $('.mainContent-left h2').text('Thanks for your Enquiry!');
                    $('.mainContent-left p').text('One of our team will be in touch soon to discuss your enquiry.');
                    //$('.mainContent-left a').replaceWith('<a class="submitAgain button" href="javascript:loadSubPage(\'contact-us\');">Submit</a>');
                    $('.mainContent-left a').replaceWith('<a class="submitAgain button" href="javascript:loadFromCache(\'contact-us\');">Submit</a>');
                }
            }
        });
    }
}

