$(document).ready(function() {

    $('.digiCertHolder').css({
            'overflow' : 'hidden',
            'height' : '56px'
        });
    // hide the all of the element with class hidden on page load
    $(".hidePanel").hide();
    // toggle 'my details' on events regs pages

    // home page button hover
    $('div.spotlightNav .userBtn img').hover(function() {
        $(this).css('left', '-252px');
    }, function() {
        $(this).css('left', '0');
    });

    // home page features hover
    $('ul.features li, ul#speakersCarousel li').hover(function() {
        $(this).addClass('hovered');
    }, function() {
        $(this).removeClass('hovered');
    });

    // speakers slider ( item scroller )
    jQuery('#speakersCarousel').jcarousel({
        scroll: 2,
        visible: 4,
        animation: 'slow',
        wrap: 'both',
        auto: 8
    });

    // sponsors slider ( item scroller )
    jQuery('#sponsorsCarousel').jcarousel({
        scroll: 1,
        visible: 7,
        animation: 'slow',
        wrap: 'both',
        auto: 8
    });

    // sponsors slider ( item scroller )
    jQuery('#exhibCarousel').jcarousel({
        scroll: 1,
        visible: 7,
        animation: 'slow',
        wrap: 'both',
        auto: 8
    });
});

// check out process
function groupBooked() {
	$('.groupBook').is(':checked') ? $(".hidePanel").show() : $(".hidePanel").hide();
}



function ShowHideFilter(hiddenfieldID, mainDivID, footerDivID, buttonImageID, headerFooterImageID) {
	if (document.getElementById(hiddenfieldID).value == 'none'
            || document.getElementById(hiddenfieldID).value == ''
            || document.getElementById(hiddenfieldID).value == null) {
		document.getElementById(hiddenfieldID).value = 'inline';
		document.getElementById(buttonImageID).src = '/Images/nav/rightbar/filter_close.gif';
		document.getElementById(headerFooterImageID).src = '/Images/nav/rightbar/filterPanelHeaderBtm1.gif';
	}
	else {
		document.getElementById(hiddenfieldID).value = 'none';
		document.getElementById(buttonImageID).src = '/Images/nav/rightbar/filter_open.gif';
		document.getElementById(headerFooterImageID).src = '/Images/nav/rightbar/filterPanelHeaderBtm2.gif';
	}

	document.getElementById(mainDivID).style.display = document.getElementById(hiddenfieldID).value;
	document.getElementById(footerDivID).style.display = document.getElementById(hiddenfieldID).value;
}

function ShowFilterPanel(hiddenfieldID, mainDivID, footerDivID, buttonImageID, headerFooterImageID) {
	document.getElementById(hiddenfieldID).value = 'inline';
	document.getElementById(buttonImageID).src = '/Images/nav/rightbar/filter_close.gif';
	document.getElementById(headerFooterImageID).src = '/Images/nav/rightbar/filterPanelHeaderBtm1.gif';
	document.getElementById(mainDivID).style.display = document.getElementById(hiddenfieldID).value;
	document.getElementById(footerDivID).style.display = document.getElementById(hiddenfieldID).value;
}

function SetFilterHiddenField(triggerID, hiddenfieldID) {
	if (document.getElementById(triggerID) && document.getElementById(hiddenfieldID)) {
		document.getElementById(hiddenfieldID).value = document.getElementById(triggerID).innerHTML;
	}
}

function SetTextBoxFilterHiddenField(triggerID, hiddenfieldID) {
	if (document.getElementById(triggerID) && document.getElementById(hiddenfieldID)) {
		document.getElementById(hiddenfieldID).value = document.getElementById(triggerID).value;
	}
}

function SetCheckBoxFilterHiddenField(checkboxID, hiddenfieldID) {
	if (document.getElementById(checkboxID) && document.getElementById(hiddenfieldID)) {
		if (document.getElementById(checkboxID).checked) {
			document.getElementById(hiddenfieldID).value = document.getElementById(checkboxID).value;
		} else {
			document.getElementById(hiddenfieldID).value = '0';
		}
	}
}

/*
=================================================================================
Stay in touch web control
=================================================================================
*/

function lclOpenUpdateForm() {
	document.getElementById("closedForm").style.display = "none";
	document.getElementById("openForm").style.display = "block";
	document.getElementById("thankYou").style.display = "none";
}

function lclCloseUpdateForm() {
	document.getElementById("closedForm").style.display = "block";
	document.getElementById("openForm").style.display = "none";
	document.getElementById("thankYou").style.display = "none";
}

function lclShowThankYou() {
	document.getElementById("closedForm").style.display = "none";
	document.getElementById("openForm").style.display = "none";
	document.getElementById("thankYou").style.display = "block";
}



function RetrieveYourFavouritesOnComplete(result, txtResult, methodName) {
	document.getElementById("divYourFavourites").innerHTML = result;
}

function YourFavouritesError(error, userContext, methodName) {
	if (error != null)
	//alert(error.get_message());
		alert("An error occured while processing your request");
}

$(document).ready(function() {
	$('#overlay').fadeTo(0, 0);
	$("a.overlayOpen").click(
	    function(event) {
	    	if ((navigator.userAgent).search(new RegExp(/msie 6\./i)) != -1) {
	    		$('select').css('visibility', 'hidden');
	    		$('#overlay').css("height", ($('body').height() + 18));
	    	} else {
	    		$('#overlay').css("height", $('body').height());
	    	}
	    	$('#overlay').css("width", $('body').width() - 22);
	    	$('#contentTop').removeClass('overlayed');
	    	$('#contentArea').removeClass('overlayed');
	    	$('#contentBottom').removeClass('overlayed');
	    	$('#someID').fadeIn();

	    	$('#overlay').css('visibility', 'visible');
	    	$('#overlay').fadeTo("slow", 0.4);
	    	if ((navigator.userAgent).search(new RegExp(/msie 6\./i)) == -1) {
	    		return false;
	    	}
	    });

	$(".overlay a#overlayClose").click(
		function(event) {
			$('#contentTop').addClass('overlayed');
			$('#contentArea').addClass('overlayed');
			$('#contentBottom').addClass('overlayed');
			$('#someID').fadeOut();
			$('#overlay').fadeTo("slow", 0.4);
			if ((navigator.userAgent).search(new RegExp(/msie 6\./i)) != -1) { $('select').css('visibility', 'visible'); }
			return false;
		}
	);


	// news listing hover
	$('div.leftBarNewsContainer ul li').hover(function() {
		$(this).addClass('even');
	}, function() {
		$(this).removeClass('even');
	});

});

function showEventOverlay() {
	$(document).ready(function() {
		$('#overlay').css("width", $('body').width() - 22);
		$('#overlay').css("height", $('body').height());
		$('#contentHolder div.content').removeClass('overlayed');
		$('#overlay').fadeTo(0, 0.4);
		$('#overlay').css('visibility', 'visible');
	});
}

function lclCheckContactForm() {

	var valid = true;

	if ($('#ctl00_ctl00_ContentPlaceHolderPageFrame_ContentPlaceHolderMain_txtName').val() == "") {
		($('#liName').addClass('formError'))
		valid = false;
	}
	else {
		($('#liName').removeClass('formError'))
	}

	if ($('#ctl00_ctl00_ContentPlaceHolderPageFrame_ContentPlaceHolderMain_txtEmail').val() == "") {
		($('#liEmail').addClass('formError'))
		valid = false;
	}
	else {
		($('#liEmail').removeClass('formError'))
	}

	if (!valid)
		$('#errorText').removeClass('hidden')
	else
		$('#errorText').addClass('hidden')

	return valid;
}

function lclShowElement(divName) {
	$('#' + divName).slideDown();
}


function lclHideElement(divName) {
	$('#' + divName).slideUp();
}

function ShowLostSessionOrderOverlay(paymentReceived, orderNumber) {
    Revolution.LayoutPath = '/Modules/Layout.aspx';
    Revolution.GenerateOverlay('showTechnicalIssues', function (o) {
        Revolution.GetLayout('TechnicalIssues&pr=' + paymentReceived + '&o=' + orderNumber, function (l) {
            $(o).find('div.overlayContentInnerContainer').html(l);
            ShowOverlayContent(o, function () {
                //callback 
            });
        });
    });
}

function ShowOverlayContent(o, c, addToWidth) {
    if (addToWidth === undefined) {
        addToWidth = 0
    }
    var renderDelay = 100;
    if ($.browser.msie) {
        renderDelay = 400;
    }
    $(o).oneTime(renderDelay, function () {
        $(o).find('div.ajaxLoaderContainer').hide();
        $(o).animate({
            width: $(o).find('div.overlayContentInner').outerWidth() + 22 - addToWidth,
            left: ($(window).width() / 2) - (($(o).find('div.overlayContentInner').outerWidth() + 32) / 2)
        }, 400, function () { $(o).find('div.overlayContentInner').css('position', 'relative'); });
        $(o).find('div.overlayContentInnerContainer').animate({
            height: $(o).find('div.overlayContentInner').outerHeight(),
            width: $(o).find('div.overlayContentInner').outerWidth()
        }, 400, function () {
            var ic = $(this);
            $(this).oneTime(400, function () {
                ic.css('height', 'auto');
            });
            if (!$.browser.msie) {
                $(o).find('div.overlayContentInner').fadeTo(0, 0).css('visibility', 'visible').fadeTo(300, 1, function () {
                    $(o).find('a.overlayClose, a.otherClose').unbind('click').click(function () {
                        $(o).hide(0, function () { $(this).remove(); });
                        $('#overlayScreen').fadeOut($(this).css('visibility', 'hidden'));
                    });
                    if (typeof (c) == 'function') { c(); }
                });
            } else {
                $(o).find('div.overlayContentInner').css('visibility', 'visible');
                $(o).find('a.overlayClose, a.otherClose').unbind('click').click(function () {
                    $(o).hide(0, function () { $(this).remove(); });
                    $('#overlayScreen').fadeOut($(this).css('visibility', 'hidden'));
                });
                if (typeof (c) == 'function') { c(); }
            }
        });
    });
}

var PiraEvents = new function() {

    this.TechnicalIssue = function() {
        Revolution.GenerateOverlay('showTechnicalIssues', function(o) {
            Revolution.GetLayout('TechnicalIssues', function(l) {
                $(o).find('div.overlayContentInnerContainer').html(l);
                ShowOverlayContent(o, function() {
                    //callback 
                });
            });
        });
    };

    this.NewRegister = function(overlayName) {
        Revolution.GenerateOverlay('showNewRegister', function(o) {
            $('.overlayed').css('z-index', '1');
            $(o).addClass('ecommOverlay');
            if ($.browser.msie) {
                if (parseInt($.browser.version) == '6') {
                    $('select').filter(function() {
                        return $(this).parents('.overlay').length < 1;
                    }).addClass('hideOverlay');
                }
            };
            Revolution.GetLayout(overlayName, function(l) {
                $(o).find('div.overlayContentInnerContainer').html(l);
                $(o).find('div.overlayContentInner').attr('id', 'piraEventsOverride');
                ShowOverlayContent(o, function() {
                    if ($.browser.msie) {
                        if (parseInt($.browser.version) == '6') {
                            $('.overlayClose').click(function() {
                                $('select').removeClass('hideOverlay');
                            });
                        }
                    };
                    $('.overlayClose').click(function() {
                        $('.overlayed').css('z-index', '99999');
                    });

                    if (overlayName == 'NewRegister') {
                        // Click event to button
                        $('#ibtnCreateAccount').unbind('click').click(function() {
                            PiraEvents.AddNewAccount();
                        });
                    }
                    else {
                        $('#ibtnCreateAccount').unbind('click').click(function() {
                            PiraEvents.AddNewEventAccount();
                        });
                    }

                    // Add 'enter key' event
                    if (overlayName == 'NewRegister') {
                        $('div.formContainer').keypress(function(e) {
                            if (e.keyCode == 13)
                                PiraEvents.AddNewAccount();
                        });
                    }
                    else {
                        $('div.formContainer').keypress(function(e) {
                            if (e.keyCode == 13)
                                PiraEvents.AddNewEventAccount();
                        });
                    }

                    // Add change event to the country dropdown to get a list of states
                    $('#ddlCountry').change(function() {
                        $.ajax({
                            type: "POST",
                            url: '/Modules/Ajax.aspx/GetStates',
                            dataType: "json",
                            data: '{"countryID" : ' + $(this).val() + '}',
                            contentType: "application/json; charset=utf-8",
                            success: function(response) {
                                // Remove existing select
                                $('#liCounty select').remove();

                                if (response.d.HTML == '') {
                                    // Hide state li if nothing is returned
                                    $('#liCounty').addClass('hidden');
                                }
                                else {
                                    // Show states
                                    $('#liCounty').append(response.d.HTML);
                                    $('#liCounty label').html(response.d.StateLabel + '<span class="mandatory">*</span>');
                                    $('#liCounty').removeClass('hidden');
                                }
                            },
                            error: function() {
                                alert("Unable to retrieve States");
                            }
                        });
                    });
                });
            });
        });
    };

    this.AddNewAccount = function() {
        // If valid, add new account
        if (PiraEvents.ValidateAccountForm()) {
            // Check user exists
            $.ajax({
                type: "POST",
                url: '/Modules/Ajax.aspx/CheckUserExists',
                dataType: "json",
                data: '{"emailAddress" : "' + trim($('#txtEmailAddress').val()) + '"}',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    var found = response.d.Found;
                    var hasCredentials = response.d.HasCredentials;

                    // The username already exists
                    if (found == true && hasCredentials == true) {
                        $('#liErrorUserAlreadyExists').removeClass('hidden');
                        $('#divErrorList').removeClass('hidden');
                        $('#liEmailAddress').addClass('formError');
                    }
                    else {
                        // The username doesn't exist so add the new user
                        var jsData = {};
                        jsData.found = found;
                        jsData.hasCredentials = hasCredentials;
                        jsData.company = trim($('#txtCompany').val());
                        jsData.address1 = trim($('#txtAddress1').val());
                        jsData.address2 = trim($('#txtAddress2').val());
                        jsData.address3 = trim($('#txtAddress3').val());
                        jsData.city = trim($('#txtCity').val());
                        jsData.postcode = trim($('#txtPostcode').val());

                        if ($('#ddlState').length > 0) {
                            jsData.stateID = parseInt($('#ddlState').val());
                        }
                        else {
                            jsData.stateID = 0;
                        }

                        jsData.countryID = parseInt($('#ddlCountry').val());
                        jsData.phone = trim($('#txtTelephone').val());
                        jsData.fax = trim($('#txtFax').val());
                        jsData.mobile = trim($('#txtMobile').val());
                        jsData.email = trim($('#txtEmailAddress').val());
                        jsData.title = trim($('#txtTitle').val());
                        jsData.firstName = trim($('#txtFirstName').val());
                        jsData.lastName = trim($('#txtSurname').val());
                        jsData.jobTitle = trim($('#txtJobTitle').val());
                        jsData.password = trim($('#txtPassword').val());
                        jsData.siteID = $('#hfSiteID').val();

                        $.ajax({
                            type: "POST",
                            url: '/Modules/Ajax.aspx/CreateEcommAccount',
                            dataType: "json",
                            data: JSON.stringify(jsData),
                            async: false,
                            contentType: "application/json; charset=utf-8",
                            success: function(response) {

                                window.location.href = response.d.URL;
                            },
                            error: function() {
                                alert('Error adding Contact');
                            }
                        });
                    }
                },
                error: function() {
                    alert("Check User failed");
                }
            });
        }
    };

    this.AddNewEventAccount = function() {
        // If valid, add new account
        if (PiraEvents.ValidateAccountForm()) {
            // Check user exists
            $.ajax({
                type: "POST",
                url: '/Modules/Ajax.aspx/CheckUserExists',
                dataType: "json",
                data: '{"emailAddress" : "' + trim($('#txtEmailAddress').val()) + '"}',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    var found = response.d.Found;
                    var hasCredentials = response.d.HasCredentials;

                    // The username already exists
                    if (found == true && hasCredentials == true) {
                        $('#liErrorUserAlreadyExists').removeClass('hidden');
                        $('#divErrorList').removeClass('hidden');
                        $('#liEmailAddress').addClass('formError');
                    }
                    else {
                        // The username doesn't exist so add the new user
                        var jsData = {};
                        jsData.found = found;
                        jsData.hasCredentials = hasCredentials;
                        jsData.company = trim($('#txtCompany').val());

                        if ($('#txtVATNumber').length > 0) {
                            jsData.vatNumber = $('#txtVATNumber').val();
                        }
                        else {
                            jsData.vatNumber = '';
                        }

                        jsData.address1 = trim($('#txtAddress1').val());
                        jsData.address2 = trim($('#txtAddress2').val());
                        jsData.address3 = trim($('#txtAddress3').val());
                        jsData.city = trim($('#txtCity').val());
                        jsData.postcode = trim($('#txtPostcode').val());

                        if ($('#ddlState').length > 0) {
                            jsData.stateID = parseInt($('#ddlState').val());
                        }
                        else {
                            jsData.stateID = 0;
                        }

                        jsData.countryID = parseInt($('#ddlCountry').val());
                        jsData.phone = trim($('#txtTelephone').val());
                        jsData.mobile = trim($('#txtMobile').val());
                        jsData.email = trim($('#txtEmailAddress').val());
                        jsData.title = trim($('#txtTitle').val());
                        jsData.firstName = trim($('#txtFirstName').val());
                        jsData.lastName = trim($('#txtSurname').val());
                        jsData.jobTitle = trim($('#txtJobTitle').val());
                        jsData.password = trim($('#txtPassword').val());

                        jsData.badgeName = trim($('#txtBadgeName').val());
                        jsData.extension = trim($('#txtExtension').val());

                        jsData.siteID = $('#hfSiteID').val();

                        $.ajax({
                            type: "POST",
                            url: '/Modules/Ajax.aspx/CreateEventAccount',
                            dataType: "json",
                            data: JSON.stringify(jsData),
                            async: false,
                            contentType: "application/json; charset=utf-8",
                            success: function(response) {
                                window.location.href = response.d.URL;
                            },
                            error: function() {
                                alert('Error adding Contact');
                            }
                        });
                    }
                },
                error: function() {
                    alert("Check User failed");
                }
            });
        }
    };

    this.ClearValidation = function() {
        // Remove box at top
        $('div.#divErrorList').addClass('hidden');
        $('div.#divErrorList ul li').each(function() {
            $(this).addClass('hidden');
        });

        // Remove styling from round text boxes
        $('.formError').each(function() {
            $(this).removeClass('formError');
        });
    };

    this.ValidateTextBox = function(textBoxID, validationMessage) {
        if (trim($('#' + textBoxID).val()) == '') {
            $('#' + textBoxID).parents('li').addClass('formError');
            $('#' + validationMessage).removeClass('hidden');
            return false;
        }
        else {
            return true;
        }
    };

    this.ValidateDropDown = function(dropDownID, validateMessage) {
        if (!$('#' + dropDownID).hasClass('hidden') && $('#' + dropDownID).val() == '0') {
            $('#' + dropDownID).parents('li').addClass('formError');
            $('#' + validateMessage).removeClass('hidden');
            return false;
        }
        else {
            return true;
        }
    };

    this.ValidateAccountForm = function() {
        var valid = true;

        // Clear existing validation styles
        PiraEvents.ClearValidation();

        // We had this before: valid && PiraEvents.ValidateTextBox('txtFirstName', 'liErrorFirstName');
        // So if the first one is invalid then when we get to the second one and test valid first, if it's false we don't bother 
        // to do the function call, because we already know the outcome to be false

        valid = PiraEvents.ValidateTextBox('txtFirstName', 'liErrorFirstName') && valid;
        valid = PiraEvents.ValidateTextBox('txtSurname', 'liErrorSurname') && valid;
        valid = PiraEvents.ValidateTextBox('txtJobTitle', 'liErrorJobTitle') && valid;
        valid = PiraEvents.ValidateTextBox('txtTelephone', 'liErrorTelephone') && valid;
        valid = PiraEvents.ValidateTextBox('txtCompany', 'liErrorCompany') && valid;
        valid = PiraEvents.ValidateTextBox('txtAddress1', 'liErrorAddress') && valid;
        valid = PiraEvents.ValidateTextBox('txtCity', 'liErrorCity') && valid;
        valid = PiraEvents.ValidateTextBox('txtPostcode', 'liErrorPostcode') && valid;
        valid = PiraEvents.ValidateTextBox('txtEmailAddress', 'liErrorEmailAddress') && valid;
        valid = PiraEvents.ValidateTextBox('txtPassword', 'liErrorPassword') && valid;
        valid = PiraEvents.ValidateTextBox('txtPasswordConfirm', 'liErrorPasswordConfirm') && valid;

        valid = PiraEvents.ValidateDropDown('ddlCountry', 'liErrorCountry') && valid;
        valid = PiraEvents.ValidateDropDown('ddlState', 'liErrorCounty') && valid;

        // Valid postcode - needed for US and Canada
        if ($('#txtPostcode').val() != '' && $('#ddlCountry').val() == 81 || $('#ddlCountry').val() == 235) {
            var postcode = $('#txtPostcode').val();

            if (postcode.length < 5 || postcode.length > 9) {
                $('#liPostcode').addClass('formError');
                valid = false;
            }
            else {

                // Extra formatting for Canada
                if ($('#ddlCountry').val() == 81) {
                    // Going to hit the server for this just to ensure existing functionality isn't lost.
                    $.ajax({
                        type: "POST",
                        url: '/Modules/Ajax.aspx/CheckCanadianPostCode',
                        dataType: "json",
                        data: '{"postcode" : "' + postcode + '"}',
                        async: false,
                        contentType: "application/json; charset=utf-8",
                        success: function(response) {
                            if (response.d.Valid == false) {
                                $('#liPostcode').addClass('formError');
                                $('#liErrorPostcode').removeClass('hidden');
                                valid = false;
                            }
                        },
                        error: function() {
                            alert("Valid postcode check failed");
                            valid = false;
                        }
                    });
                }
            }

        }

        // Validate phone number
        if ($('#txtTelephone').val() != '') {
            var phone = $('#txtTelephone').val();
            $.ajax({
                type: "POST",
                url: '/Modules/Ajax.aspx/ValidatePhone',
                dataType: "json",
                data: '{"phone" : "' + phone + '"}',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    if (response.d.Valid == false) {
                        $('#liTelephone').addClass('formError');
                        $('#liErrorTelephoneInvalid').removeClass('hidden');
                        valid = false;
                    }
                },
                error: function() {
                    alert("Validate phone number failed");
                    valid = false;
                }
            });
        }

        // Validate emailaddress
        if ($('#txtEmailAddress').val() != '' && !validateEmail($('#txtEmailAddress').val())) {
            $('#liEmailAddress').addClass('formError');
            $('#liErrorEmailAddressInvalid').removeClass('hidden');
            valid = false;
        }

        // Validate password and check it matches confirm
        if ($('#txtPassword').val() != '') {
            var password = $('#txtPassword').val();

            // Hit server to check p/w in correct format
            $.ajax({
                type: "POST",
                url: '/Modules/Ajax.aspx/ValidatePassword',
                dataType: "json",
                data: '{"password" : "' + password + '"}',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    if (response.d.Valid == false) {
                        $('#liPassword').addClass('formError');
                        $('#liErrorPasswordInvalid').removeClass('hidden');
                        valid = false;
                    }
                    else {
                        // If it's valid, check the confirm matches
                        if (password != $('#txtPasswordConfirm').val()) {
                            $('#liPassword').addClass('formError');
                            $('#liPasswordConfirm').addClass('formError');
                            $('#liErrorPasswordNotMatched').removeClass('hidden');
                            valid = false;
                        }
                    }
                },
                error: function() {
                    alert("Valid password check failed");
                    valid = false;
                }
            });
        }

        if (!valid) {
            $('div.#divErrorList').removeClass('hidden');
        }
        else {
            $('div.#divErrorList').addClass('hidden');
        }

        return valid;
    };

    this.GroupInfo = function() {
        Revolution.GenerateOverlay('showGroupInfo', function(o) {
            $(o).addClass('ecommOverlay');
            if ($.browser.msie) {
                if (parseInt($.browser.version) == '6') {
                    $('select').filter(function() {
                        return $(this).parents('.overlay').length < 1;
                    }).addClass('hideOverlay');
                }
            }
            Revolution.GetLayout('GroupInfo', function(l) {
                $(o).find('div.overlayContentInnerContainer').html(l);
                ShowOverlayContent(o, function() {
                    if ($.browser.msie) {
                        if (parseInt($.browser.version) == '6') {
                            $('.overlayClose').click(function() {
                                $('select').removeClass('hideOverlay');
                            });
                        }
                    };
                    $('#divGroupXStandard').html(eventXStandard.groupInfo);
                });
            });
        });
    };

    this.ShowEditOrganiserOverlay = function () {
        Revolution.GenerateOverlay('editDelegate', function (o) {
            $('.overlayed').css('z-index', '1');
            $(o).addClass('ecommOverlay');
            if ($.browser.msie) {
                if (parseInt($.browser.version) == '6') {
                	$('select').filter(function () {
                		return $(this).parents('.overlay').length < 1;
                	}).addClass('hideOverlay');
                }
            };
            Revolution.GetLayout("EditOrganiser", function (l) {
            	$(o).find('div.overlayContentInnerContainer').html(l);
            	$(o).find('.overlayContentInner').attr('id', 'piraEventsOverride');

                var jsData = {};

                ShowOverlayContent(o, function () {
                	if ($.browser.msie) {
                		if (parseInt($.browser.version) == '6') {
                			$('.overlayClose').click(function () {
                				$('select').removeClass('hideOverlay');
                			});
                		}
                	};
                	$('.overlayClose').click(function () {
                		$('.overlayed').css('z-index', '99999');
                	});

                	// Populate data
                	$.ajax({
                		type: "POST",
                		url: '/Modules/Ajax.aspx/GetOrganiserDetails',
                		dataType: "json",
                		data: JSON.stringify(jsData),
                		async: false,
                		contentType: "application/json; charset=utf-8",
                		success: function (response) {
                			$('#txtTitle').val(response.d.Title);
                			$('#txtFirstName').val(response.d.FirstName);
                			$('#txtSurname').val(response.d.Surname);
                			$('#txtCompany').val(response.d.Company);
                			$('#txtJobTitle').val(response.d.JobTitle);
                			$('#txtEmailAddress').val(response.d.Email);
                			$('#txtBadgeName').val(response.d.BadgeName);
                			$('#txtTelephone').val(response.d.Telephone);

                			// Click event to button
                			$('#ibtnEditDelegate').unbind('click').click(function () {
                				PiraEvents.EditOrganiser(response.d.RelationshipID, response.d.AddressID);
                			});

                			$('div.formContainer').keypress(function (e) {
                				if (e.keyCode == 13)
                					PiraEvents.EditOrganiser(response.d.RelationshipID, response.d.AddressID);
                			});
                		},
                		error: function () {
                			alert('Error editing Contact');
                		}
                	});

                });
            });
        });
    };

    this.EditOrganiser = function (relationshipID, addressID) {
        if (PiraEvents.ValidateEditOrganiser()) {
            // Check user exists
            $('.ajaxLoader.editNext').show().css('opacity', '0.7');
            var jsData = {};

            jsData.phone = trim($('#txtTelephone').val());
            jsData.email = trim($('#txtEmailAddress').val());
            jsData.title = trim($('#txtTitle').val());
            jsData.firstName = trim($('#txtFirstName').val());
            jsData.lastName = trim($('#txtSurname').val());
            jsData.company = trim($('#txtCompany').val());

            jsData.jobTitle = trim($('#txtJobTitle').val());
            jsData.phone = trim($('#txtTelephone').val());
            jsData.email = trim($('#txtEmailAddress').val());

            if (trim($('#txtBadgeName').val()) != '') {
                jsData.badgeName = trim($('#txtBadgeName').val());
            }
            else {
                jsData.badgeName = '';
            }

            jsData.addressID = addressID;
            jsData.relationshipID = relationshipID;

            $.ajax({
                type: "POST",
                url: '/Modules/Ajax.aspx/EditOrganiser',
                dataType: "json",
                data: JSON.stringify(jsData),
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (response) {

                $('.ajaxLoader.editNext').hide();
                $('#tbDelegate').html(response.d.HTML);
                	$('.organiserError').hide();
                	$('#editDelegate').remove();

                	$('.overlayed').css('z-index', '99999');
                },
                error: function () {
                	alert('Error editing Contact');
                }
            });
        }
    };

    this.ValidateEditOrganiser = function () {
        var valid = true;

        // Clear existing validation styles
        PiraEvents.ClearValidation();

        // We had this before: valid && PiraEvents.ValidateTextBox('txtFirstName', 'liErrorFirstName');
        // So if the first one is invalid then when we get to the second one and test valid first, if it's false we don't bother 
        // to do the function call, because we already know the outcome to be false

        valid = PiraEvents.ValidateTextBox('txtFirstName', 'liErrorFirstName') && valid;
        valid = PiraEvents.ValidateTextBox('txtSurname', 'liErrorSurname') && valid;
        valid = PiraEvents.ValidateTextBox('txtJobTitle', 'liErrorJobTitle') && valid;
        valid = PiraEvents.ValidateTextBox('txtTelephone', 'liErrorTelephone') && valid;
        valid = PiraEvents.ValidateTextBox('txtCompany', 'liErrorCompany') && valid;
        valid = PiraEvents.ValidateTextBox('txtEmailAddress', 'liErrorEmailAddress') && valid;


        // Validate phone number
        if ($('#txtTelephone').val() != '') {
            var phone = $('#txtTelephone').val();
            $.ajax({
                type: "POST",
                url: '/Modules/Ajax.aspx/ValidatePhone',
                dataType: "json",
                data: '{"phone" : "' + phone + '"}',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                	if (response.d.Valid == false) {
                		$('#liTelephone').addClass('formError');
                		$('#liErrorTelephoneInvalid').removeClass('hidden');
                		valid = false;
                	}
                },
                error: function () {
                	alert("Validate phone number failed");
                	valid = false;
                }
            });
        }

        // Validate emailaddress
        if ($('#txtEmailAddress').val() != '' && !validateEmail($('#txtEmailAddress').val())) {
            $('#liEmailAddress').addClass('formError');
            $('#liErrorEmailAddressInvalid').removeClass('hidden');
            valid = false;
        }


        if (!valid) {
            $('div.#divErrorList').removeClass('hidden');
        }
        else {
            $('div.#divErrorList').addClass('hidden');
        }

        return valid;
    };
	
    this.TabXHR = undefined;

    function ShowOverlayContent(o, c, addToWidth) {
        if (addToWidth === undefined) {
            addToWidth = 0;
        }
        var renderDelay = 100;
        if ($.browser.msie) {
            renderDelay = 400;
        }
        $(o).oneTime(renderDelay, function() {
            $(o).find('div.ajaxLoaderContainer').hide();
            $(o).animate({
                width: $(o).find('div.overlayContentInner').outerWidth() + 22 - addToWidth,
                left: ($(window).width() / 2) - (($(o).find('div.overlayContentInner').outerWidth() + 32) / 2)
            }, 400, function() { $(o).find('div.overlayContentInner').css('position', 'relative'); });
            $(o).find('div.overlayContentInnerContainer').animate({
                height: $(o).find('div.overlayContentInner').outerHeight(),
                width: $(o).find('div.overlayContentInner').outerWidth()
            }, 400, function() {
                var ic = $(this);
                $(this).oneTime(400, function() {
                    ic.css('height', 'auto');
                });
                if (!$.browser.msie) {
                    $(o).find('div.overlayContentInner').fadeTo(0, 0).css('visibility', 'visible').fadeTo(300, 1, function() {
                        $(o).find('a.overlayClose, a.otherClose').unbind('click').click(function() {
                            $(o).hide(0, function() { $(this).remove(); });
                            $('#overlayScreen').fadeOut($(this).css('visibility', 'hidden'));
                        });
                        if (typeof (c) == 'function') { c(); }
                    });
                } else {
                    $(o).find('div.overlayContentInner').css('visibility', 'visible');
                    $(o).find('a.overlayClose, a.otherClose').unbind('click').click(function() {
                        $(o).hide(0, function() { $(this).remove(); });
                        $('#overlayScreen').fadeOut($(this).css('visibility', 'hidden'));
                    });
                    if (typeof (c) == 'function') { c(); }
                }
            });
        });
    }
};

function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
}
function submitCodes(evt) {
	//look for the window.event in case event isnt passed in
	
	var keyCode;
	evt = evt || window.event;
	keyCode = evt.keyCode || evt.which;
	
	if(keyCode == 13) {
		
		return EcommBasket.CheckProduct();;
		
	}
	return true;
}
