

// ===========================================
// = Initialize MillerCoors Shared Framework =
// ===========================================

var mcf = new mcFramework('wrapper','av_container');
mcf.mcSetSiteCode('mgd64');
mcf.mcSetAVContent('Please enter your date of birth to continue.');
mcf.mcSetCallbackFunction(initPage);
mcf.mcSetAVTag(avtag);
mcf.mcSetAVFailTag(avfailtag);
//mcf.mcSetAVFailForward(false); //Uncomment this line to temporarily disable forwarding to thecoolspot.com

// ================================
// = AV and AV Fail Tag Functions =
// ================================

function avtag() {
	trackPage('pagename=2009 MGD64 AV: Home,channel=2009 MGD64 AV,floodlight=mgd64263,atlas=Homepage_ageveri_image');
}

function avfailtag() {
	trackPage('pagename=2009 MGD64 AV: Fail,channel=2009 MGD64 AV');
}

// ============================
// = On Content Load Function =
// ============================

function initPage() {
	var params = {
		quality: "high",
		scale: "noscale",
		wmode: "opaque",
		allowscriptaccess: "always",
		bgcolor: "#FFFFFF"
	};
	var flashvars = {
		siteXML: "xml/site.xml"
	};
	var attributes = {id:"content"};
	swfobject.embedSWF("main.swf", "content", "100%", "100%", "9.0.124", "expressInstall.swf", flashvars, params, attributes);
	
}
function setFlashToHome() {
	var flashMovie=getSwf("content");
	flashMovie.setAddressToHome();
}

// =========================
// = Overlay Functionality =
// =========================

function launchOverlay(curOverlay) {
	centerDiv('locator');
	overlay.show();
}

// Live Servlet Url: http://locator.mgd64.com/APLocator.aspx
// Stage Servlet: http://stage.locator.mgd64.com/APLocator.aspx
// Live API Key: ABQIAAAADEfJitKfoB_llxtJ0rnnRRRb3kwNYQPP1xvvoiT9riYhx8FbOxQgMTmvOS7R9JkyiH1saOXf3-izjw
// Stage API Key: ABQIAAAADEfJitKfoB_llxtJ0rnnRRT53z8mcN83kGiMmHozY09lTTwp_BSvFgztQkS7FlL7p1Dlleypf8QeGQ

var overlay = {
	show: function() {
		var flashvars = {
			widget: 'false',
			baseURL: 'http://locator.mgd64.com/APLocator.aspx',
			apiKey: 'ABQIAAAADEfJitKfoB_llxtJ0rnnRRRb3kwNYQPP1xvvoiT9riYhx8FbOxQgMTmvOS7R9JkyiH1saOXf3-izjw'
		}
		var attributes = {}
		var params = {
			wmode: "transparent",
			align: "middle",
			scale: "showall",
			allowFullScreen: "false"
		}
		swfobject.embedSWF("assets/swf/mgd64_locator.swf", "locator_flash", "750", "540", "9.0.124", "expressInstall.swf", flashvars, params, attributes);
		
		$('#locator').show();
	},
	hide: function() {
		$('#locator').hide();
		setFlashToHome();
	}
}


// ================
// = Sign Up =
// ================

function launchSignUp() {
	centerDiv('signup');
	$('#signup').show();
	trackPage('pagename=2009 MGD 64 E-mail Sign Up: Home,channel=2009 MGD 64 E-mail Sign Up,floodlight=mgd64149,atlas=Homepage_EmailSignUpLink_image');
}


/* ========================== */
/* = Summer Sweeps Overlay Launch = */
/* ========================== */

function launchSummer() {
	centerDiv('SummerSweeps');
	$('#SummerSweeps').show();
	$('#SummerSweeps_intro').show();
	trackPage('pagename=MGD 64 - Do More with MGD 64: State Select,channel=MGD 64 - Do More with MGD 64');
}
function showSummerSweepsForm(){
	$('#SummerSweeps_intro').hide();
	$('#SummerSweeps_form').show(); 
	$('#SummerSweepsForm').show();
}

function closeSummerSweeps() {
    $('#SummerSweepsForm').show();
	$('#SummerSweeps_intro').hide();
	$('#SummerSweeps_form').hide(); 
	$('#SummerSweeps').hide();
	$('.formField').val('');
	$('#mcMobileInput').hide();
	$('#errorBox').hide();
    $("#SummerSweeps_NationalDisclaimer").show();
    $("#SummerSweeps_CaliforniaDisclaimer").show();
    $("#SummerSweeps_californiaForm").hide();
    $("#SummerSweeps_nationalForm").hide();
    $("#SummerSweeps_Footer").css("top", "457px");
    $("#summerTerms").hide();
    $("#summerRules").hide();
    $("#SummerSweeps_californiaSuccess").hide();
    $("#SummerSweeps_nationalSuccess").hide();
    $("#SummerSweeps_californiaEntered").hide();
    $("#SummerSweeps_nationalEntered").hide();
    $("#SummerSweeps_form").css("background", "url('../assets/images/SummerSweeps/formPackage.png') 408px 319px no-repeat");
    $('input[title]').each(function() {
        if ($(this).val() === '') {
            $(this).val($(this).attr('title'));
        }
    });

    $("#SummerSweeps_StateDrop").val("0");
	
	resetCheckboxes();
	$("input[type='text']").removeClass("errorState");
	$("ddlState").css("background", "#ffffff");
	$("#officialRulesLabel").css("color", "#000000");
	$("#errorBox").hide();
	
	setFlashToHome();
	
}

$(document).ready(function() {

    $("#signup_form").validate({
        submitHandler: function(form) {
            $('#signup_confirm').show();
            trackPage('pagename=2009 MGD 64 E-mail Sign Up: Confirmation,channel=2009 MGD 64 E-mail Sign Up');
        },
        invalidHandler: function(form, validator) {
            $('#error_message').html('<div style="color: #E6260F;text-weight:bold;">Please correct the highlighted fields below.</div>');
        }
    });


    $("#moptin").bind("click", function() {
        if ($('#moptin').attr('checked')) {
            $('#mobile_confirmation').show();
        }
    });

    $("#accept").bind("click", function() {
        $('#mobile_confirmation').hide();
    });

    $("#decline").bind("click", function() {
        $('#moptin').attr('checked', '')
        $('#mobile_confirmation').hide();
    });

    $("#signup_close").bind("click", function() {
        $('#signup').hide();
        setFlashToHome();
    });

    $("#holidayPromo_close").bind("click", function() {
        $('#holidayPromo').hide();

        setFlashToHome();
    });

    $("#SummerSweeps_StateSubmit").bind("click", function() {
        var theSelectedState = $("#SummerSweeps_StateDrop option:selected").text();
        if (theSelectedState != "State") {
            //display form

            $("#SummerSweeps_form").show();
            $("#SummerSweeps").css("background", "transparent url(../assets/images/SummerSweeps/background.png) no-repeat scroll left top");
            $("#SummerSweeps_intro").hide();
            $("#SummerSweeps_Footer").css("top", "526px");
            if (theSelectedState == "California") {
                $("#SummerSweeps_NationalDisclaimer").hide();
                $("#SummerSweeps_californiaForm").show();
                $("#summerTerms").show();
                $("#SummerSweeps_form").css("background", "url('../assets/images/SummerSweeps/formPackage.png') 528px 319px no-repeat");
                $("#getCode").attr("href", "assets/images/SummerSweeps/terms.html");
                $("#packCodeLegend").html("Offical Discount Code");
                $("#rulesLegend").html("Offer Agreement");
                $("#codeClick").html("Don't have an offical discount code? <a id='getCode' target='_blank' href='assets/images/SummerSweeps/terms.html'>Click here.</a>");
                trackPage('pagename=MGD 64 - Do More with MGD 64: California entry form,channel=MGD 64 - Do More with MGD 64');
            }
            else {
                $("#SummerSweeps_CaliforniaDisclaimer").hide();
                $("#SummerSweeps_nationalForm").show();
                $("#summerRules").show();
                $("#SummerSweeps_form").css("background-image", "url('../assets/images/SummerSweeps/formCard.png')");
                $("#getCode").attr("href", "assets/images/SummerSweeps/rules.html");
                $("#packCodeLegend").html("Offical Entry Code");
                $("#rulesLegend").html("Sweepstakes Agreement");
                $("#codeClick").html("Don't have an offical code? <a id='getCode' target='_blank' href='assets/images/SummerSweeps/rules.html'>Click here.</a>");
                trackPage('pagename=MGD 64 - Do More with MGD 64: National entry form,channel=MGD 64 - Do More with MGD 64');
            }
            $("#ddlState").val(theSelectedState);
            $("#SummerSweeps_form").show();
            //$("#disclaimer").css("top", "490px");

        }

    });

    //in field labels summer form
    $('input[title]').each(function() {
        if ($(this).val() === '') {
            $(this).val($(this).attr('title'));
        }

        $(this).focus(function() {
            if ($(this).val() === $(this).attr('title')) {
                $(this).val('').addClass('focused');
            }
        });

        $(this).blur(function() {
            if ($(this).val() === '') {
                $(this).val($(this).attr('title')).removeClass('focused');
            }
        });
    });

    //Summer Form
    $("#chkMobileSub").bind("click", function() {
        if ($('#chkMobileSub').attr('checked')) {
            $('#mcMobileConfirmation').show();
        } else {
            document.getElementById('txtMobileArea').value = '';
            document.getElementById('txtMobilePrefix').value = '';
            document.getElementById('txtMobileSuffix').value = '';
            $('#mcMobileInput').hide();
        }
    });

    $("#chkMobileSub2").bind("click", function() {
        if ($('#chkMobileSub2').attr('checked')) {
            $('#mcMobileConfirmation2').show();
        } else {
            document.getElementById('txtMobileArea2').value = '';
            document.getElementById('txtMobilePrefix2').value = '';
            document.getElementById('txtMobileSuffix2').value = '';
            $('#mcMobileInput2').hide();
        }
    });

    $("#accept").bind("click", function() {
        $('#mcMobileConfirmation').hide();
        $('#mcMobileInput').show();
    });

    $("#decline").bind("click", function() {
        $('#chkMobileSub').attr('checked', '');
        $('#mcMobileConfirmation').hide();
        document.getElementById('txtMobileArea').value = '';
        document.getElementById('txtMobilePrefix').value = '';
        document.getElementById('txtMobileSuffix').value = '';
        $('#mcMobileInput').hide();

    });

    $("#accept2").bind("click", function() {
        $('#mcMobileConfirmation2').hide();
        $('#mcMobileInput2').show();
    });

    $("#decline2").bind("click", function() {
        $('#chkMobileSub2').attr('checked', '');
        $('#mcMobileConfirmation2').hide();
        document.getElementById('txtMobileArea2').value = '';
        document.getElementById('txtMobilePrefix2').value = '';
        document.getElementById('txtMobileSuffix2').value = '';
        $('#mcMobileInput2').hide();

    });
    $("#SubmitSweeps").bind("click", function() {
        var formValid = verifyFields();
        if (formValid == true) {
            submitForm();
        }
    });

    $("#SubmitSpring").bind("click", function() {
        var formValid = verifyFields2();
        if (formValid == true) {
            submitSpringForm();
        }
    });

});

function launchSpringIntoAction() {
    centerDiv('SpringIntoAction');
    $('#SpringIntoAction').show();
    $('#SpringIntoAction_intro').show();
    trackPage('pagename=2010 MGD64 Spring Into Action: Intro,channel=2010 MGD64 Spring Into Action');
}
function showSpringIntoActionForm() {
    $('#SpringIntoAction_intro').hide();
    $('#SpringIntoAction_form').show();
    $('#SpringIntoActionForm').show();
    trackPage('pagename=2010 MGD64 Spring Into Action: Form,channel=2010 MGD64 Spring Into Action');
}

function closeSpringIntoAction() {
    $('#SpringIntoAction_intro').hide();
    $('#SpringIntoAction_form').hide();

    $('#SpringIntoAction_entered').hide();
    $('#SpringIntoAction_download').hide();
    $('#SpringIntoAction').hide();
    $('.formField').val('');
    $('#mcMobileInput2').hide();
    $('#errorBox').hide();
    $('input[title]').each(function() {
        if ($(this).val() === '') {
            $(this).val($(this).attr('title'));
        }
    });

    resetCheckboxes();
    $("input[type='text']").removeClass("errorState");
    $("ddlState2").css("background-color", "#ffffff");
    $("ddlState2").val("0");
    $("#officialRulesLabel2").css("color", "#000000");
    $("#errorBox").hide();

    setFlashToHome();

}


// ==============
// = Center Div =
// ==============

function centerDiv(div) {
	var div = $('#' + div);
	var height = $(window).height();
	var width = $(document).width();

  div.css({
  	'left' : width/2 - (div.width() / 2),  // half width - half element width
  	'top' : height/2 - (div.height() / 2), // similar
  	'z-index' : 15                        // make sure element is on top
  });
}



// ==========================
// = Popup Window Functions =
// ==========================

var swfId = "mbc_mainSwf";

function getSwf( id ) 
{
  if ( navigator.appName.indexOf( "Microsoft" ) != -1 ) { return window[ id ]; }
  else { return document[ id ]; }
}

function launchActiveTerms() {
  var name = Math.round( 9999*Math.random( ) ) + new Date( ).getTime( );
  var win = window.open("active_terms.html","FooterLinks" + name,"toolbar=0,menubar=0,width=400,height=325,status=0,resizable=1,scrollbars=1" );
  if( !win ) { getSwf(swfId).openWindowFromSwf( "active_terms.html" ); }
  else { winNew.focus( ); }
}

function getWidget() {
	window.open("locator/get_widget.html", "getwidget","status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=400,height=420");
	trackPage('pagename=MGD64 Product Locator: Get Widget,channel=MGD 64 Product Locator');
}
// ==========================
// = Popup Window Functions =
// ==========================

var swfId = "mbc_mainSwf";

function getSwf( id ) 
{
  if ( navigator.appName.indexOf( "Microsoft" ) != -1 ) { return window[ id ]; }
  else { return document[ id ]; }
}

function launchActiveTerms() {
  var name = Math.round( 9999*Math.random( ) ) + new Date( ).getTime( );
  var win = window.open("active_terms.html","FooterLinks" + name,"toolbar=0,menubar=0,width=400,height=325,status=0,resizable=1,scrollbars=1" );
  if( !win ) { getSwf(swfId).openWindowFromSwf( "active_terms.html" ); }
  else { winNew.focus( ); }
}

function getWidget() {
	window.open("locator/get_widget.html", "getwidget","status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=400,height=420");
	trackPage('pagename=MGD64 Product Locator: Get Widget,channel=MGD 64 Product Locator');
}

var RGlobalPackCodeList = '64CARD,MGD64,SUMMER,SUMMER64,64SUMMER,RMFX9F3M7K,"RMFX9F3M7K",';

//Summer Sweeps functions

function onShowMessage(result) {
    if (result == true) {
        $("#loading").hide();
        $('#SummerSweeps_form').hide();
        if ($("#ddlState").val() == "California") {
            $('#SummerSweeps_californiaSuccess').show();
            trackPage('pagename=MGD 64 - Do More with MGD 64: California entry confirmation,channel=MGD 64 - Do More with MGD 64');
        }
        else {
            $('#SummerSweeps_nationalSuccess').show();
            
            trackPage('pagename=MGD 64 - Do More with MGD 64: National Entry Confirmation,channel=MGD 64 - Do More with MGD 64');
        }
       
    }
    else {
        $("#loading").hide();
        $('#SummerSweeps_form').hide();
        if ($("#ddlState").val() == "California") {
            $('#SummerSweeps_californiaSuccess').show();
            trackPage('pagename=MGD 64 - Do More with MGD 64: California entry confirmation,channel=MGD 64 - Do More with MGD 64');
        }
        else {
            $('#SummerSweeps_nationalEntered').show();
           
            trackPage('pagename=MGD 64 - Do More with MGD 64: National Already Entered,channel=MGD 64 - Do More with MGD 64');
        }
        
    }
}

function OnTimeout(error) {
    alert("Stack Trace: " + error.get_stackTrace() + "/r/n" +
        "Error: " + error.get_message() + "/r/n" +
        "Status Code: " + error.get_statusCode() + "/r/n" +
        "Exception Type: " + error.get_exceptionType() + "/r/n" +
        "Timed Out: " + error.get_timedOut());
}

function OnError(error) {
    alert("Stack Trace: " + error.get_stackTrace() + "/r/n" +
        "Error: " + error.get_message() + "/r/n" +
        "Status Code: " + error.get_statusCode() + "/r/n" +
        "Exception Type: " + error.get_exceptionType() + "/r/n" +
        "Timed Out: " + error.get_timedOut());
}

function resetCheckboxes() {
    $('#chkMobileSub').attr('checked', '');
    $('#chkEmailSub').attr('checked', '');
    $('#chkOfficialRules').attr('checked', '');
    $('#rbMale').attr('checked', '');
    $('#rbFemale').attr('checked', '');
    $('#chkMobileSub2').attr('checked', '');
    $('#chkEmailSub2').attr('checked', '');
    $('#chkOfficialRules2').attr('checked', '');
    $('#rbMale2').attr('checked', '');
    $('#rbFemale2').attr('checked', '');
}

function submitForm() {
    $('#mcMobileInput').hide();
    $("#SummerSweepsForm").hide();
    $("#loading").show();
    var emailOptIn = $('#chkEmailSub').attr('checked');
    var mobileOptIn = $('#chkMobileSub').attr('checked');
    var gender = $('#rbMale').attr('checked') ? "Male" : "NotApplicable";

    if (gender == "NotApplicable") {

        gender = $('#rbFemale').attr('checked') ? "Female" : "NotApplicable";
    }

    MGD64.WebFormServices.ISweeps.SubmitRegistrationForm($('#txtPackCode').val().toUpperCase(), $("#txtFirstName").val(), $("#txtLastName").val(), "US", $("#txtStreetAddress").val(), $("#txtApartment").val(), $("#txtCity").val(), $("#ddlState").val(), $("#txtZipCode").val(), $("#txtPhoneArea").val(), $("#txtPhonePrefix").val(), $("#txtPhoneSuffix").val(), $("#txtEmail").val(), $("#txtDOBMonth").val(), $("#txtDOBDay").val(), $("#txtDOBYear").val(), gender, emailOptIn, mobileOptIn, $("#txtMobileArea").val(), $("#txtMobilePrefix").val(), $("#txtMobileSuffix").val(), onShowMessage, OnTimeout, OnError);
    //form.submit();
} 

function IsNumeric(input) {
    return (input - 0) == input && input.length > 0;
}

//Spring Sweeps functions

function submitSpringForm() {
    $('#mcMobileInput').hide();
    $("#SpringIntoActionForm").hide();
    $("#loading2").show();
    var emailOptIn = $('#chkEmailSub2').attr('checked');
    var mobileOptIn = $('#chkMobileSub2').attr('checked');
    var gender = $('#rbMale2').attr('checked') ? "Male" : "NotApplicable";

    if (gender == "NotApplicable") {

        gender = $('#rbFemale2').attr('checked') ? "Female" : "NotApplicable";
    }

    MGD64.WebFormServices.TdbFormService.SubmitCheckEmail($("#sourceIdField2").val(), $("#txtFirstName2").val(), $("#txtLastName2").val(), "US", $("#txtStreetAddress2").val(), $("#txtApartment2").val(), $("#txtCity2").val(), $("#ddlState2").val(), $("#txtZipCode2").val(), $("#txtPhoneArea2").val(), $("#txtPhonePrefix2").val(), $("#txtPhoneSuffix2").val(), $("#txtEmail2").val(), $("#txtDOBMonth2").val(), $("#txtDOBDay2").val(), $("#txtDOBYear2").val(), gender, emailOptIn, mobileOptIn, $("#txtMobileArea2").val(), $("#txtMobilePrefix2").val(), $("#txtMobileSuffix2").val(), onShowMessage2, OnTimeout, OnError);
    //form.submit();
}

function onShowMessage2(result) {
    if (result == true) {
        $("#loading2").hide();
        $('#SpringIntoAction_download').show();
        $('#SpringIntoAction_form').hide();
        trackPage('pagename=2010 MGD64 Spring Into Action: Download,channel=2010 MGD64 Spring Into Action');
    }
    else {
        $("#loading2").hide();
        $('#SpringIntoAction_entered').show();
        $('#SpringIntoAction_form').hide();
        trackPage('pagename=2010 MGD64 Spring Into Action: Fail,channel=2010 MGD64 Spring Into Action');
    }
}