var $ = jQuery.noConflict();

//Carousel
jQuery(document).ready(function($) {
    jQuery('.car1').jcarousel({
        // Configuration goes here
    });
});

//Menu
$(document).ready(function() {
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
			
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
			
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}


	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 100, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$("ul#nav li .sub").css({'display':'none'});
	$("ul#nav li").hoverIntent(config);

});

//Tweets
function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}


//Make ampersands lush
$(document).ready(function() {
    $("*:contains('&')", document.body)
        .contents()
        .each(
            function() {
                if( this.nodeType == 3 ) {
                    $(this)
                        .replaceWith( this
                            .nodeValue
                            .replace( /&/g, "<b class='amp'>&amp;</b>" )
                        );
                }
            }
        );
});

//Open in external windows
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;


//Trigger lightbox

$(document).ready(function() { 
	 $("#lg").fancybox(); 
	// $("a#inline").fancybox({ 'hideOnContentClick': true }); 
	// $("a.fbg").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': false }); 
}); 



//JQuery Plugin: "EqualHeights"  Copyright (c) 2008 Filament Group. Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
//******************************************************************************************************************************************
jQuery(document).ready(function($){ 	
	function equalHeight(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight($ ( "#footer .widget" ) );
	
});

jQuery(document).ready(function($){ 	
	function equalHeight2(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight2($ ( ".define_level .describe.g2" ) );
	
});

jQuery(document).ready(function($){ 	
	function equalHeight3(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight3($ ( ".define_level .describe.g3" ) );
	
});

jQuery(document).ready(function($){ 	
	function equalHeight4(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight4($ ( ".overview_tabs .g2 .widget" ) );
	
});

jQuery(document).ready(function($){ 	
	function equalHeight5(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight5($ ( "#contact_footer .g3" ) );
	
});



//To Top
$(document).ready(function() {
	var defaults = {
		containerID: 'moccaUItoTop', // fading element id
		containerHoverClass: 'moccaUIhover', // fading element hover class
		scrollSpeed: 1200,
		easingType: 'linear' 
	};
	
	$().UItoTop({ easingType: 'easeOutQuart' });
	
});

//Fading quotes 

$(document).ready(
function(){
	$('.lovely_words .inner').innerfade({
		animationtype: 'fade',
		speed: 'medium',
		timeout: 12000,
		type: 'sequence',
		containerheight: '250px'
	});
});

//Toggles

//Tog
$(document).ready(function(){

	//Hide (Collapse) the toggle containers on load
	$(".toggle_container").hide(); 

	//Switch the "Open" and "Close" state per click
	$(".trigger").toggle(function(){
		$(this).addClass("active");
		}, function () {
		$(this).removeClass("active");
	});

	//Slide up and down on click
	$(".trigger").click(function(){
		$(this).next(".toggle_container").slideToggle("fast");
	});

});



/*******************************Old stuff i hesitate to delete*************************************************/

		
/**
	* Function to get an element by it's ID parameter in both IE and Mozilla based browsers.
	*/
function acceptConditions()
{
	return getElement("accept_field_0").checked ? true : alert('You must accept the terms and conditions to continue');
}
	
function getElement(id)
{
	if(document.all)
	{
		return document.all[id];
	}
	else if(document.getElementById)
	{
		return document.getElementById(id);
	}
	else
	{
		for(iLayer = 1; iLayer < document.layers.length; iLayer++)
		{
			if(document.layers[iLayer].id == id)
			{
				return document.layers[iLayer];
			}
		}
	}
	return null;
}

/**
	* Set an input value
	*/
function setValue(id, value)
{
	var obj = getElement(id);
	obj.value = value;
}

/**
    * Submits a form with the specified ID, action and optional validate function
    */
function submitForm(form_id, form_action, validate)
{
    // Set default value for validate if no argument is passed
    $("#submit_button").disabled = true;
    var validate = (validate == null) ? true : validate();
    if (validate)
    {
        var form = getElement(form_id);
        try
        {
            if(form_action != "")
            {
                form.elements.action.value = form_action;
            }
            form.submit();
        }
        catch(error)
        {
            alert("There was an error:\n\n"+error.description);
        }
    }
}

/**
    * Hide or show a block level element
    */
function toggleVisible(id)
{
    var obj = getElement(id);
    if(obj.style.display == "block")
    {
        obj.style.display = "none";
    }
    else if(obj.style.display == "none")
    {
        obj.style.display = "block";
    }
    else
    {
        obj.style.display = "block";
    }
}

/**
    * Goto the specified URL
    */
function gotoUrl(url)
{
    document.location.href=url;
}


// Nick Jones, Feb 2008
// Reveals a number of hidden objects on page dependent on Select Box option
// function showSelect(id of Select Box, id prefix to Reveal - eg "attendee" will reveal "attendeeXX", "attendeeXX+1" up to option value, transition selects the effect - either show/hide immediately or slideUp/slideDown (default slide))
function showSelect(select_id, hidden_id, transition)
{
    if (!transition) transition = "slide";
    var select_box = getElement(select_id);
    try
    {
        var num = parseInt(select_box.options[select_box.selectedIndex].value);
        // Show chosen number of hidden objects
        for( var i=1 ; i<=num ; i++ )
        {
            transition == "slide" ? $("#"+hidden_id+i).slideDown(800) : $("#"+hidden_id+i).show();
        }
        // Hide the rest of them if they are visible
        var max = select_box.options[select_box.options.length-1].value;
        for( var i=num+1 ; i<=max ; i++ )
        {
            transition == "slide" ? $("#"+hidden_id+i).slideUp(800) : $("#"+hidden_id+i).hide();
        }
    }
    catch(error)
    {
        alert("There was an error:\n\n"+error.description);
    }
}

// Updates HTML object content based on given source (eg form item), target ID, event and any value to blank the field
function updateText(textbox_id, target_id, e, blank)
{
    if (e)
    {
        var key = (window.event) ? event.keyCode : e.keyCode;
    }
    else
    {
        var key = 0;
    }   
    
    switch(key)
    {
        case 9:
        case 16:
//          break;
        case 13:
            //alert("input#"+textbox_id+".text_field");
            //tmp = jQuery.inArray("input#"+textbox_id+".text_field", $(":text"));
            //tmp = $(":text"); //[].focus();;
        default:
//          if ( typeof(textbox_id) == "string") $(target_id).html(textbox_id);
            if ( (element = getElement(textbox_id)) ? element.value : 0 )
            {
                switch(element.type)
                {
                    case "select-one":
                        if (!element.selectedIndex || element.options[element.selectedIndex].text == blank)
                        {
                            $(target_id).html("");
                        }
                        else
                        {
                            $(target_id).html(element.options[element.selectedIndex].text);
                        }
                        break;
                    default:
                        (typeof(blank) != 'undefined' && element.value == blank) ? $(target_id).html("") : $(target_id).html(element.value);
                        break;
                }
            }
            break;
    }
    
}

function showVisibleSlide(id,focus)
{
    var obj = $("#"+id);
    obj.animate( { height: "show", opacity: "show" }, 200, function() {
        if ( focus ) $("#"+focus).focus();
    } );
}


function hideVisibleSlide(id,focus)
{
    var obj = $("#"+id);
    obj.animate( { height: "hide", opacity: "hide" }, 200, function() {
        if ( focus ) $("#"+focus).focus();
    } );
}

function toggleVisibleSlide(id,focus)
{
    var obj = $("#"+id);
    if ( obj[0].style.display == "none" )
    {
        showVisibleSlide(id,focus);
    }
    else
    {
        hideVisibleSlide(id,focus);
    }
}


// Takes text as input and converts all formatting to HTML formatting
function displayParagraph(text)
{
    return (text) ? text.replace(/\n/g,"<br />") : "";
}

function showTab(tabgroupName, tabName) {
    var tabGroup = getElement(tabgroupName);
    var menuItems = tabGroup.getElementsByTagName("ul")[0].getElementsByTagName("li");
    for (var i=0; i<menuItems.length ; i++ ) {
        if (menuItems[i].id == (tabName + "_tab")) {
            getElement(menuItems[i].id.substring(0,menuItems[i].id.length-4)).style.display = "";
            menuItems[i].className += " current";
        } else {
            getElement(menuItems[i].id.substring(0,menuItems[i].id.length-4)).style.display = "none";
            var curPos = menuItems[i].className.indexOfGBR("current");
            if (curPos != -1) {
                var className = menuItems[i].className;
                menuItems[i].className =  className.substring(0,curPos-1);
                if (className.length > curPos + 7) menuItems[i].className += className.substring(curPos+7,className.length);
            }
        }
    }
}

function hideEditProfile(id)
{
    $("#"+id+"_edit").animate( { opacity: "hide", paddingTop: 0, paddingBottom: 0 }, 100, function() {
        $("#"+id+"_view").animate( { opacity: "show" }, 100 );
    });
}

function edit(section_id,focus_id)
{
    $("#"+section_id+"_view").animate( { opacity: "hide", paddingTop: 0, paddingBottom: 0 }, 100, function() {
        $("#"+section_id+"_edit").animate( { opacity: "show" }, 100, function() {
            getElement(focus_id).focus();
        });
    });
}

function go(folder)
{
    var department = $("#department_field").val();
    var day = $("#day_field").val();
    var path = window.location.pathname;
    if (department != -1 && day != -1) window.location.href = "http://www.a4uexpo.com" + folder + department + "/" + day + "/";
}

function goList()
{
    params = new Array();
    if ($("#order_field").val() != 0) params.push("o");
    if ($("#sort_field").val()) params.push("s="+$("#sort_field").val());
    window.location.href = "http://www.a4uexpo.com/london/exhibitor_list.php?" + params.join("&");
}

// Takes any string and converts it into a form that can be used in SEO-optimised URLs, eg converts "It's Not Working" to "its-not-working"
function SEOEncode(string)
{
    return string.toLowerCase().replace(/'/g,"").replace(/ /g,"-").replace(/\(/g,"").replace(/\)/g,"");
}

function showMenu(id)
{
	$(document).ready(function(){
		/*
		var class_name = ($("#"+id+" dt a").attr("class"));
		$("#"+id+" dt a").removeClass();
		$("#"+id+" dt a").addClass(class_name+"_current");
		*/
		//$("#"+id+" dd").slideDown("slow");
		$("#"+id+" dd").show();
	});
}

function checkCountry(selectbox)
{
    if(selectbox.options[selectbox.selectedIndex].value == "GBR")
    {
        showVisibleSlide('id_postcode_spn');
        showVisibleSlide('id_billing_postcode_spn');
    }
    else
    {
        hideVisibleSlide('id_postcode_spn');
        hideVisibleSlide('id_billing_postcode_spn');
    }
    if(selectbox.options[selectbox.selectedIndex].value == "NLD")
    {
        showVisibleSlide('div_lab_dutch-vat-number');
        showVisibleSlide('div_fields_dutch-vat-number');
    }
    else
    {
        hideVisibleSlide('div_lab_dutch-vat-number');
        hideVisibleSlide('div_fields_dutch-vat-number');
    }
}


// Adds much needed regex support to jquery's selectors!
// See http://james.padolsey.com/javascript/regex-selector-for-jquery/
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}


//fades 
$(document).ready(
function(){
	$('.home_fade').innerfade({
		animationtype: 'fade',
		speed: 'slow',
		timeout: 6000,
		type: 'sequence',
		containerheight: '216px'
	});
});


/*
//Pre and ap ends
jQuery(document).ready(function($){$(".addclass").prepend('add stuff');});

//Add class
jQuery(document).ready(function($){$('').addClass("none");});

//Fade in
jQuery(document).ready(function($){$('').fadeIn(2000);});


//Open in external windows
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;

//JQuery Plugin: "EqualHeights" by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com) Copyright (c) 2008 Filament Group. Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
jQuery(document).ready(function($){ 	
	function equalHeight(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight($ ( "add stuff" ) );
	
});

*/
