$(document).ready(function()
{
    if($('#termsandconditionsmodal').length == 1)
    {
        $('#termsandconditionsmodal').load(_baseUrl + 'TermsAndConditions.aspx #termscontainer');
    }
    
    $('.fancybox_auto').fancybox({
        autoDimensions: false,
        width: '80%',
        height: '80%'
    });
    
    $('.emailicon').fancybox({
        autoDimensions: true
    });
    
    $('#topLinkEmailSubscribe').fancybox({
        autoDimensions: true
    });
    
    // set up magazine
    $('.mag').hide();
    $('.mag:last').show();
    
    // temporary "preview" warning
    //var previewMsg = $('<div id="preview-message"><p>Welcome to the <strong>Businesslife.co Preview</strong>.<br/>We are pleased to introduce you to our new web presence, but please be advised that we are still fine-tuning some elements of the site.<br/><strong>Your feedback is very much appreciated.</strong> <a href="'+_baseUrl+'Contact.aspx">Click here to contact us</a>.</div>').prependTo(document.body).slideDown(500);

    // dynamic IE6 warning
    if($.browser.msie && $.browser.version.substring(0,1) == '6')
    {
        $('<div id="ie-warning-container"></div>').load(_baseUrl + 'IE6Warning.aspx #ie-warning', function()
        {
            $(this).prependTo(document.body).slideDown(500);
        });
    }        
    
    if(!$.cookie('hideemailprompt'))
    {
        $('#emailprompt').dialog(
        {
            position: ['right'], //,'top'],
            close: function()
            {
                $.cookie("hideemailprompt", true,
                {
                    expires: 365
                }
                );
            }
        });
    }    
    else    
    {
        $('#emailprompt').hide();
    }
});

function EmailPromptYes()
{
    AnalyticsTrackEvent('Email', 'Prompt', 'Yes');
    $('#emailprompt').dialog('close');
    $('#topLinkEmailSubscribe').click();
}

function EmailPromptNo()
{
    AnalyticsTrackEvent('Email', 'Prompt', 'No');
    $('#emailprompt').dialog('close');
}

/* Magazine switcher in framework */
function Magazine_ShowNext()
{
    var currentId = $('.mag:visible').attr('id').replace('issue', '');

    var next = $('#issue' + (parseInt(currentId,10) + 1));

    if($(next).length == 0)
    {
        var next = $('.mag:first');
    }

    $('.mag:visible').hide("slide", { direction: "left" }, 500, function()
    {
        $(next).show("slide", { direction: "right" }, 500);
    });
}

function Magazine_ShowPrevious()
{
    var currentId = $('.mag:visible').attr('id').replace('issue', '');

    var next = $('#issue' + (parseInt(currentId,10) - 1));

    if($(next).length == 0)
    {
        var next = $('.mag:last');
    }

    $('.mag:visible').hide("slide", { direction: "right" }, 500, function()
    {
        $(next).show("slide", { direction: "left" }, 500);
    });
}

function EnsureTermsAndConditions()
{
    if($('#termsandconditions input[type=checkbox]:checked').length != 1)
    {
        alert('You must agree to the businesslife.co terms and conditions in order to proceed.');

        return false;
    }
    
    return true;
}

function UpdateBusinessNewsPreview()
{
    $('#previewContainer').html('<strong>Building preview, please wait...</strong>');
    $.ajax({
        url: _baseUrl + 'handlers/SubmitNewsPreview.ashx',
        type: 'POST',
        cache: false,
        async: false,
        data: 
        ({
            name: $('.previewName').val(),
            date: $('.previewDate').val(),
            body: $('.previewBody').val(),
            title: $('.previewTitle').val(),
            image: $('.previewImage').attr('src'),
            imageRight: ($('input[type=radio]:checked').val() == 'right')
        }),
        dataType: 'html',
        success: function(data)
        {
            $('#previewContainer').html(data);
        },
        error: function()
        {
            $('#previewContainer').html('<strong>Failed to generate preview, please try again.</strong>');
        }
    });
}

function AnalyticsTrackEvent(type, action, detail)
{
    try
    {
       _gaq.push(['_trackEvent', type, action, detail]);
    }
    catch(ex)
    {
    }
}

function DoNewsletterSubscription()
{
    var email = $('#usEmailAddress').val();
    var news = ($('#usBusinessNews:checked').length==1?true:false);
    var commentary = ($('#usCommentary:checked').length==1?true:false);
    var features = ($('#usFeatures:checked').length==1?true:false);

    if(email.length < 6 || email.indexOf('@') < 1 || email.lastIndexOf('.') < 3)
    {
        $('#usEmailAddress').focus();
        alert('Please enter a valid email address');
        return;               
    } 

    if(!news && !commentary && !features)
    {
        if(!confirm('Are you sure you wish to subscribe without receiving any regular updates? For regular emails, please click cancel and tick the relevant boxes before clicking subscribe again.'))
        {
            return;
        }
    }
    
    $.ajax({
        url: _baseUrl + 'handlers/Newsletter.ashx',
        type: 'POST',
        cache: false,
        async: false,
        data: 
        ({
            email: email,
            news: news,
            commentary: commentary,
            features: features
        }),
        dataType: 'html',
        success: function(data)
        {
            alert('Your subscription has been processed. You will receive an email shortly - please click the link in this message to confirm your subscription.');
            $.fancybox.close();    
        },
        error: function()
        {
            alert('There was a problem while processing your subscription. Please check your email address is correct and try again.');
        }
    });    
}

function UpdateSubscriptionPrice()
{
    if($('.subscriptiontype option:selected').text().indexOf('(') > 0)
    {
        var value = $('.subscriptiontype option:selected').text();        
        value = value.substring(value.indexOf('(') + 1, value.lastIndexOf(')'));
        $('#priceinfo').html('Total cost including postage (and GST, where applicable): ' + value + '. Your subscription will be created on a recurring basis via PayPal. Please click continue to proceed to payment.');        
    }
    else
    {
        $('#priceinfo').html('');
    }
}

function SubmitNewsOnClick()
{
    if(!Page_ClientValidate('news')) 
    { 
        alert('Please ensure you have completed all required fields.'); 
    } 
    else 
    { 
        alert('Please wait for a moment while your article is submitted. You will be shown a confirmation page once the process is complete.');
        $('.submitcontainer a').hide(); 
    }
}
